# Search Test Coverage — Test-Engineering Plan This plan follows `sources/task-brief.md`. Because the deliverable is a regression test suite for existing behaviour, the steps use implementation prompts rather than artificial pairs of test and production-code prompts. Each prompt is intended for a separate turn; review the changes and run the relevant checks before moving to the next step, adapting subsequent prompts to what was actually found. The goal is at least 20 additional test methods across nine search categories, with at least 80% statement coverage individually for `search_views.py` and `search/search_objects.py`. Existing endpoint contracts must remain unchanged. ### Step 1 - Establish Search Contracts and the Test Baseline **Implementation prompt:** - Inspect the existing search tests, search views, SearchObjects implementation, URL routing, forms, permission helpers, and relevant models. Map the main, customer, organisation, group, user, sprint, tag, notification, and permission-set search categories to their endpoints. For each one, identify request parameters, response structure, matching rules, ordering, pagination, closed-state support, and access rules. Distinguish main-search object types from the nine endpoint categories; do not assume all categories share one contract. - Configure the documented Python environment using a virtual environment, and run the existing search suite with verbose output. Capture baseline test counts and failures, and measure baseline coverage for the two target modules. Also establish the full-suite baseline so later failures can be classified accurately. Report environment blockers and actual command output rather than claiming success. Don't change production code or add tests yet; give me a concise contract map and a proposed set of at least 20 new test methods. ### Step 2 - Build Deterministic Search Test Data and the First Result Assertions **Implementation prompt:** - Using the contracts found from Step 1, introduce minimal reusable test setup following the repository's conventions. Prefer Django TestCase and setUpTestData where compatible. Avoid a broad fixture rewrite or transactional tests without a concrete need. Create synthetic users, groups, permissions, object assignments, and a small dataset with deliberately matching, near-matching, unrelated, and restricted records. Control timestamps only where they affect behaviour under test. - Add initial result-level tests for customer and organization search, addressing their explicit TODOs. Assert exact returned identities and exposed counts, with positive and negative cases, rather than merely HTTP statuses. Keep the fixture design understandable and extend it only when later steps need additional data. Run the new tests and existing search suite, and report the exact commands and results. Do not remove a TODO until its intended coverage exists. ### Step 3 - Cover Main Search Object Selection and Result Structure **Implementation prompt:** - Expand main-search result tests even though that section has no explicit TODO. The existing main-search methods check HTTP statuses, including for a numeric query and include_closed, but do not verify returned records. Distinguish the search page endpoint, which renders the interface, from search_data, which returns the actual JSON results; posting to the page is not a substitute for testing the data endpoint. - Exercise each of SearchObjects' six configured types: kanban_board, project, request_for_change, requirement, requirement_item, and task. Use validated form choices to confirm which types are reachable through the public endpoint. Assert the normalised id, title, and status values, along with each selected type's number_of3a-3_pages and current_page metadata. Verify both single-type selection and a multi-type request: unrequested types should not appear, and matching objects should stay in their own result lists. Use records sharing a title or numeric ID across types to detect accidental cross-type mixing. - Test a selected type with no matches: its result list should be empty and its page metadata should reflect the actual contract. Do not invent a total-count field; the current helper exposes page counts. Use subtests for repeated type mappings rather than creating superficial copies of the same test. Run the focused tests and existing search suite, and report any configured type that the form does not actually expose. ### Step 4 - Add Result Assertions for the Remaining Search Categories **Implementation prompt:** - Add meaningful result-level coverage for group, user, sprint, tag, notification, and permission-set searches. Reuse the test setup where it makes the tests clearer, but preserve each endpoint's distinct access and request rules. Cover matching and exclusion, no-match results, and response totals where available. Add partial, case-insensitive, and multi-term variants only where the inspected endpoint contract supports them. - Use descriptive test methods and subtests for closely related input variants. Keep at least 20 additional test methods as the overall target rather than treating subtest iterations as separate methods. Run the affected tests and existing search suite. Report which of the nine categories now have exact result assertions and which still need work. REWRITEN - Add useful search results tests for group, user, sprint, tag, notification, and permission-set searches. Reuse as much setup as possible where it makes the tests clearer, but preserve each endpoint's distinct access and request rules. Cover matching and exclusion, no-match results, and response totals where available. Only test partial, case-insensitive, and multi-term searches on endpoints that support them. Use clear test names and subtests for similar inputs. Write at least 20 new test methods (subtests don’t count). Run the new tests and the existing search tests. Tell me which of the nine categories now have exact result checks and which don’t. ### Step 5 - Verify Permissions and Result Isolation **Implementation prompt:** - Add to permission tests using ordinary users with explicit group and permission assignments. For endpoints using ObjectAssignment-based visibility, assert both that authorised records are returned and restricted records are absent. Cover users with no relevant access and an object reachable through multiple accessible groups, checking that identities and counts are not duplicated. Verify that inaccessible matches do not inflate returned totals. - Test administrative endpoints against their actual access rules rather than assuming group-based visibility applies everywhere. For notifications, verify recipient isolation where the contract supports it. Keep superuser behaviour in separate tests so it cannot hide missing permission setup. Run the permission cases and existing search suite, and summarise the access boundaries each test protects. Do not alter production permissions as part of this step. REWRITTEN - Add permission tests that use normal users with set groups and permissions. For endpoints that use ObjectAssignment to control what users can see, check two things - allowed records show up, and restricted records do not. Test users with no access. Test an object that a user can reach through more than one group, and check that it is not listed twice and the counts are not doubled. Check that matches the user cannot access do not add to the totals. - Test admin endpoints against their real access rules. Don't assume group-based visibility applies everywhere. For notifications, check that each user only sees their own, where the contract allows it. Keep superuser tests separate so they cannot hide missing permission setup. Run the new permission tests and the existing search tests. Then write a short summary of the access limits each test protects. Do not change any production permissions in this step. ### Step 6 - Exercise Pagination and Closed-State Boundaries **Implementation prompt:** - For main search, explicitly cover the distinct closed-status branches: RFC statuses 5 and 6, kanban's Closed string, and the higher-order Closed status on the remaining supported types. Verify include_closed changes status filtering without restoring deleted or inaccessible records. Exercise per-type pagination in a multi-type request, including different page counts and an empty list for a type whose results are exhausted. Test zero and negative destination_page inputs against the existing first-page slicing behaviour, and distinguish slice selection from the echoed current_page metadata; raise any misleading metadata as a contract question rather than silently redefining it. - Add pagination tests only for endpoints that actually paginate. Create enough controlled records to test page one, page two, the final page boundary, and a page beyond the results. Assert exact membership, page sizes, totals, and metadata where exposed, and verify there is no overlap or loss across valid pages. Respect documented or implemented invalid-page handling and assert ordering only when it is part of the contract. - For each search path supporting closed/include_closed filtering, create accessible open and closed records and verify the default behaviour and supported toggle values. Include a restricted closed record to ensure enabling the toggle cannot bypass visibility filtering. Where an endpoint lacks either feature, record that limitation instead of adding it. Run the new cases and the entire search suite, then report results and any unresolved contract questions. REWROTE - For the main search, test each kind of "closed" status on its own: RFC statuses 5 and 6, the "Closed" text value for kanban, and the higher-level "Closed" status on the other supported types. Check that include_closed changes the status filter, but does'nt bring back deleted records or records the user can't access. Test paging for each type in a request that covers many types. Use different page counts, and include an empty list for a type that has run out of results. Test destination_page values of zero and negative numbers against the current first-page behavior. Keep two things apart: which slice of results is returned, and the current_page value that is sent back. If the current_page value is misleading, raise it as a question about the contract. Do not quietly change what it means. - Add pagination tests only for endpoints that actually paginate. Create test records to check page one, page two, the last page, and a page past the end. Check the exact records on each page, the page sizes, the totals, and the page info if the endpoint returns it. Make sure no records repeat or go missing across valid pages. Follow the documented or actual handling of invalid pages. Check the order of records only if the order is part of the contract. - For each search path that supports closed or include_closed filtering, create open and closed records the user can access. Check the default behavior and each supported toggle value. Add a closed record the user cannot access, to prove that turning on the toggle doesn't skirt around visibility rules. If an endpoint is missing either feature, note that gap. Do not add the feature. Run the new tests and the full search suite. Then report the results and any open questions about the contract. 7 ### Step 3A - Cover Main Search Text and Numeric Matching **Implementation prompt:** - Add focused main-search tests for the matching branches in SearchObjects. Verify exact and partial title matches, case-insensitive matching, and multi-term AND logic. Include a full match, a first-term-only match, a second-term-only match, and an unrelated record so replacing AND with OR would fail the test. Verify empty and no-match queries against the validated form behaviour. - Cover numeric tokens with intentionally controlled data: one record matching by primary key but not title, another matching a numeric substring in its title but having a different primary key, and an unrelated record. Both legitimate matches should be returned. Add a mixed text/numeric query to prove that the numeric ID-or-title condition still combines with the other token using AND. Cover the RFC's rfc_id mapping and the requirement item's own ID, not just the default task mapping. - Keep datasets below the page limit unless pagination is the subject of the test. Do not assume unsupported tokenization, fuzzy matching, exact-only numeric matching, or stable ordering. Run the focused tests and search suite. If the existing behaviour conflicts with the specified contract, explain the problems before modifying production code or accepting it as correct. 8 ### Step 3B - Cover Main Search Visibility and Soft Deletion **Implementation prompt:** - Add main-search-specific visibility tests using real users, groups, memberships, and ObjectAssignment rows. Verify that an ordinary user can't get around group visibility by sending include_all_groups. For a superuser, separately work the default group-limited behaviour and the explicit include_all_groups opt-in: the current helper bypasses group limits only when both conditions hold. Don't assume superusers always see every object. - Verify that soft-deleted objects remain absent even when include_closed or the superuser all-groups option is enabled. Isolate deleted ObjectAssignment and deleted UserGroup cases: Avoid accidentally granting access by giving each test record only the relationship under examination. Assert both visible and excluded identities and the resulting page metadata. - Add requirement-item tests proving that access follows the parent requirement's assignment, while returned and numerically searched IDs belong to the requirement item itself. Intentionally give the parent and child different IDs so using the wrong key is detectable. Include an inaccessible parent's item and an item with overlapping authorised group assignments. Check with the later general permission step so these cases are not repeated. Run the focused tests and search suite without changing production visibility rules. 9 ### Step 3C - Cover Exclusion of Already-Linked Main Search Results **Implementation prompt:** - Inspect the real callers of exclude_destination and exclude_location_id, then build tests for supported source/destination combinations used to find objects available for linking. Create a matching object already linked to the specified destination, an unlinked match, and a match linked only to a different destination. Assert that only the link to the requested destination excludes a record. - Add a soft-deleted assignment case to prove that an inactive link does not incorrectly exclude an otherwise visible match. Keep the active group assignment granting visibility separate from the destination link being tested. Exercise omission of either exclusion parameter according to the existing form/helper contract, and assert that exclusion affects the returned page count before pagination. Use representative real combinations, including special ID mappings only where supported; do not generate a Cartesian product of speculative object relationships. - Run the focused tests and search suite. Explain any genuine defect exposed by these cases and ask before changing production code. The objective is to cover the existing linking workflow, not create a new exclusion API. 10 ### Step 7 - Check Test Sensitivity and Close Coverage Gaps **Implementation prompt:** - Review the new suite against the brief's coverage checklist: exact/partial matching, case handling, multi-term AND logic, empty/no-match results, pagination, permissions, closed-state filtering, counts, and all nine search categories. Include the expanded main-search checks for six configured object types, numeric ID/title matching, selected-type isolation, parent-based requirement-item access, soft deletion, the all-groups opt-in, and exclusion of already-linked objects. Treat at least 20 additional test methods as a floor, not a cap or a reason to split repetitive assertions into artificial tests. Identify missing cases using both that checklist and a fresh coverage report. Run coverage with NearBeach.views.search_views and NearBeach.views.search as the source modules, and report uncovered lines for both target files. - Check representative tests for sensitivity: temporarily give a result assertion a deliberately wrong expected identity or count and confirm that the focused test fails for that reason, then restore the correct assertion and rerun it. Keep these checks temporary, do not leave failing assertions or modified production logic behind, and report what was actually verified. Review that assertions reject incorrect results rather than merely exercising branches. 11 ### Step 8 - Run Final Regression Checks and Review the Diff **Implementation prompt:** - Review the final diff for unnecessary fixture changes, duplicated setup, brittle ordering assumptions, mocks that bypass real search behaviour, and accidental production changes. Confirm that each of the nine search categories has meaningful result assertions. Remove addressed TODOs only where justified; leave unrelated gaps alone. - Run the search suite with verbose output, the agreed coverage command and report, and the complete existing Django suite. Compare the results with the baseline, explicitly separating pre-existing failures and environment blockers from new regressions. Report the commands, actual test counts, individual coverage percentages for both target modules, changed test and fixture files, and any remaining limitations. Do not describe the task as complete unless the agreed acceptance criteria have been checked; surface any unmet criterion plainly.