Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

step-03b-subagent-backend.md 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. ---
  2. name: 'step-03b-subagent-backend'
  3. description: 'Subagent: Generate backend tests only (unit, integration, contract)'
  4. subagent: true
  5. outputFile: '/tmp/tea-automate-backend-tests-{{timestamp}}.json'
  6. ---
  7. # Subagent 3B-backend: Generate Backend Tests
  8. ## SUBAGENT CONTEXT
  9. This is an **isolated subagent** running in parallel with API test generation (and optionally E2E test generation for fullstack projects).
  10. **What you have from parent workflow:**
  11. - Target features/services identified in Step 2
  12. - Knowledge fragments loaded: test-levels-framework, test-priorities-matrix, data-factories
  13. - Config: test framework, detected stack type
  14. - Coverage plan: which services/modules need backend testing
  15. **Your task:** Generate backend tests ONLY (unit, integration, contract - not API endpoint tests, not E2E).
  16. ---
  17. ## MANDATORY EXECUTION RULES
  18. - Read this entire subagent file before acting
  19. - Generate backend tests ONLY (unit, integration, contract)
  20. - Output structured JSON to temp file using the subagent output schema contract
  21. - Follow knowledge fragment patterns
  22. - Do NOT generate API endpoint tests (that's subagent 3A)
  23. - Do NOT generate E2E tests (that's subagent 3B-E2E)
  24. - Do NOT run tests (that's step 4)
  25. - Do NOT generate fixtures yet (that's step 3C aggregation)
  26. ---
  27. ## SUBAGENT TASK
  28. ### 1. Identify Test Targets
  29. From the coverage plan (Step 2 output), identify:
  30. - Which services/modules need unit test coverage
  31. - Which integrations need integration test coverage (database, message queues, external services)
  32. - Which service contracts need contract test coverage (Pact, schema validation)
  33. - Business logic functions requiring edge case coverage
  34. ### 2. Detect Framework & Language
  35. From `config.test_framework` and project manifests, determine:
  36. - **Python (pytest)**: Use `pytest` conventions, `conftest.py` fixtures, `@pytest.mark` decorators
  37. - **Java/Kotlin (JUnit)**: Use JUnit 5 annotations (`@Test`, `@BeforeEach`, `@Nested`), Mockito for mocking
  38. - **Go (go test)**: Use `*_test.go` files, `testing.T`, table-driven tests, `testify` assertions
  39. - **C#/.NET (xUnit)**: Use `[Fact]`, `[Theory]`, `[InlineData]`, `Moq` for mocking
  40. - **Ruby (RSpec)**: Use `describe`/`context`/`it` blocks, `let`/`before` helpers, `FactoryBot`
  41. ### 3. Generate Unit Tests
  42. For each module/service, create test files following language-idiomatic patterns:
  43. **Python (pytest) example:**
  44. ```python
  45. import pytest
  46. from unittest.mock import MagicMock, patch
  47. from myapp.services.user_service import UserService
  48. class TestUserService:
  49. """[P0] Unit tests for UserService"""
  50. def test_create_user_with_valid_data(self, user_factory):
  51. """Should create user when data is valid"""
  52. user_data = user_factory.build()
  53. result = UserService.create(user_data)
  54. assert result.email == user_data["email"]
  55. def test_create_user_rejects_duplicate_email(self, user_factory):
  56. """[P1] Should reject duplicate email"""
  57. user_data = user_factory.build(email="existing@test.com")
  58. with pytest.raises(DuplicateEmailError):
  59. UserService.create(user_data)
  60. ```
  61. **Go (go test) example:**
  62. ```go
  63. func TestUserService_Create(t *testing.T) {
  64. tests := []struct {
  65. name string
  66. input CreateUserInput
  67. wantErr bool
  68. }{
  69. {"valid user", validInput(), false},
  70. {"duplicate email", duplicateInput(), true},
  71. }
  72. for _, tt := range tests {
  73. t.Run(tt.name, func(t *testing.T) {
  74. svc := NewUserService(mockRepo)
  75. _, err := svc.Create(tt.input)
  76. if (err != nil) != tt.wantErr {
  77. t.Errorf("Create() error = %v, wantErr %v", err, tt.wantErr)
  78. }
  79. })
  80. }
  81. }
  82. ```
  83. **Requirements:**
  84. - Follow the detected framework's idiomatic test patterns
  85. - Include priority tags [P0], [P1], [P2], [P3] in test descriptions
  86. - Use proper mocking for external dependencies (database, APIs, message queues)
  87. - Test both happy path and error cases
  88. - Use proper typing/type hints where applicable
  89. - No hard-coded test data; use factories or builders
  90. ### 4. Generate Integration Tests
  91. For service integrations, create integration test files:
  92. - Database integration tests (with test database or in-memory alternatives)
  93. - Message queue consumer/producer tests
  94. - Cache integration tests
  95. - External service integration tests (with mocked HTTP clients)
  96. ### 5. Generate Contract Tests (if applicable)
  97. If the project uses microservices or has defined API contracts:
  98. - Pact consumer/provider tests
  99. - Schema validation tests (JSON Schema, Protobuf)
  100. - OpenAPI spec compliance tests
  101. ### 6. Track Fixture Needs
  102. Identify fixtures/helpers needed for backend tests:
  103. - Database fixtures (seed data, cleanup)
  104. - Factory functions (test data builders)
  105. - Mock services (HTTP mocks, message queue mocks)
  106. - Configuration fixtures (test environment config)
  107. **Do NOT create fixtures yet** - just track what's needed for aggregation step.
  108. ---
  109. ## OUTPUT FORMAT
  110. Write JSON to temp file: `/tmp/tea-automate-backend-tests-{{timestamp}}.json`
  111. ```json
  112. {
  113. "subagentType": "backend",
  114. "testsGenerated": [
  115. {
  116. "file": "tests/unit/test_user_service.py",
  117. "content": "[full test file content]",
  118. "description": "Unit tests for UserService",
  119. "priority_coverage": {
  120. "P0": 3,
  121. "P1": 2,
  122. "P2": 1,
  123. "P3": 0
  124. }
  125. },
  126. {
  127. "file": "tests/integration/test_user_repository.py",
  128. "content": "[full test file content]",
  129. "description": "Integration tests for user database operations",
  130. "priority_coverage": {
  131. "P0": 1,
  132. "P1": 2,
  133. "P2": 1,
  134. "P3": 0
  135. }
  136. }
  137. ],
  138. "coverageSummary": {
  139. "totalTests": 15,
  140. "testLevels": ["unit", "integration", "contract"],
  141. "fixtureNeeds": ["databaseFixture", "userFactory", "mockHttpClient"]
  142. },
  143. "status": "complete",
  144. "success": true,
  145. "subagent": "backend-tests",
  146. "knowledge_fragments_used": ["test-levels-framework", "test-priorities-matrix", "data-factories"],
  147. "summary": "Generated 15 backend test cases (10 unit, 4 integration, 1 contract)"
  148. }
  149. ```
  150. **On Error:**
  151. ```json
  152. {
  153. "subagentType": "backend",
  154. "testsGenerated": [],
  155. "coverageSummary": {
  156. "totalTests": 0,
  157. "testLevels": [],
  158. "fixtureNeeds": []
  159. },
  160. "status": "partial",
  161. "success": false,
  162. "subagent": "backend-tests",
  163. "error": "Error message describing what went wrong",
  164. "partial_output": {
  165. /* any tests generated before error */
  166. }
  167. }
  168. ```
  169. ---
  170. ## EXIT CONDITION
  171. Subagent completes when:
  172. - All identified modules have backend test files generated
  173. - All tests follow language-idiomatic patterns
  174. - JSON output written to temp file using the subagent output schema contract
  175. - Fixture needs tracked
  176. **Subagent terminates here.** Parent workflow will read output and proceed to aggregation.
  177. ---
  178. ## SUBAGENT SUCCESS METRICS
  179. ### SUCCESS:
  180. - All backend tests generated following idiomatic patterns
  181. - JSON output valid and complete, matches subagent output schema contract
  182. - No E2E or browser tests included (out of scope)
  183. - Proper mocking used for external dependencies
  184. - Priority tags assigned to all test cases
  185. ### FAILURE:
  186. - Generated tests other than backend tests (unit/integration/contract)
  187. - Did not follow language-idiomatic patterns
  188. - Invalid or missing JSON output
  189. - Output schema does not match the contract
  190. - Ran tests (not subagent responsibility)
  191. - Used real external services instead of mocks