Docsity

WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 PYTEST & SECURITY UNIT TESTING
WORKBOOK 48 PRACTICE TESTS, PYTHON SECURITY,
API TESTING & VULNERABILITY VERIFICATION 2026
50 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Design and implement secure unit tests using pytest advanced features (fixtures, parametrization,
mocking)
2 Identify and verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated
tests
3 Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions
4 WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests
5 Python Security
6 API Testing & Vulnerability Verification 2026
7 Foundations of Software Security & Python Testing
8 Applied Software Security & Python Testing
9 Advanced Software Security & Python Testing
10 Software Security & Python Testing Review
ABSTRACT
This study document brings together 50 carefully worded exam questions drawn from WGU D385
Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API Testing &
Vulnerability Verification 2026, with the strongest emphasis placed on Design and implement
secure unit tests using pytest advanced features (fixtures, parametrization, mocking), Identify and
verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated tests and
Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions. Every
item follows the wording style and level of reasoning you meet in the real paper, and each one is
paired with a clear rationale so the correct choice is never a guess. Work through the set at your
own pace, mark the questions that slow you down, then come back to them until the reasoning
feels automatic. Learners who revise this way walk into the exam room recognising the pattern
behind the questions instead of meeting them for the first time. Keep going - steady, honest
practice is what turns a difficult paper into a comfortable pass.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API and more Exams Computer Security in PDF only on Docsity!

WGU D385 PYTEST & SECURITY UNIT TESTING

WORKBOOK 48 PRACTICE TESTS, PYTHON SECURITY,

API TESTING & VULNERABILITY VERIFICATION 2026

50 QUESTIONS

TABLE OF CONTENTS

TOPIC

1 Design and implement secure unit tests using pytest advanced features (fixtures, parametrization, mocking) 2 Identify and verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated tests 3 Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions 4 WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests 5 Python Security 6 API Testing & Vulnerability Verification 2026 7 Foundations of Software Security & Python Testing 8 Applied Software Security & Python Testing 9 Advanced Software Security & Python Testing 10 Software Security & Python Testing Review

ABSTRACT

This study document brings together 50 carefully worded exam questions drawn from WGU D Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API Testing & Vulnerability Verification 2026, with the strongest emphasis placed on Design and implement secure unit tests using pytest advanced features (fixtures, parametrization, mocking), Identify and verify common vulnerabilities (injection, broken auth, XSS) in Python APIs via automated tests and Integrate SAST/DAST tools and fuzzing into CI/CD pipelines to detect security regressions. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.

Q1 DESIGN AND IMPLEMENT SECURE UNIT TESTS USING PYTEST ADVANCED FEATURES

(FIXTURES, PARAMETRIZATION, MOCKING)

A pytest test uses @pytest.mark.parametrize with 1000 test cases and a

session-scoped fixture that opens a database connection. The test fails

intermittently due to a race condition when run in parallel with pytest-xdist. Which

configuration change best ensures deterministic test outcomes?

A. Change the fixture to function scope and use a transaction rollback per test. CORRECT B. Use @pytest.mark.flaky to retry failed tests automatically. C. Set --dist=loadscope to group tests by module and share the session fixture. D. Replace the session fixture with a global variable initialized at import time. RATIONALE: A function-scoped fixture with transaction rollback isolates each test, preventing shared-state races. Flaky retries mask the issue; loadscope still shares state across workers; global variables worsen isolation.

Q2 DESIGN AND IMPLEMENT SECURE UNIT TESTS USING PYTEST ADVANCED FEATURES

(FIXTURES, PARAMETRIZATION, MOCKING)

When testing an API endpoint that returns a JWT, which pytest assertion most

effectively verifies that the token's signature cannot be tampered with?

A. Decode the JWT payload and assert the 'alg' header is 'none'. B. Use a known secret to re-sign a modified payload and assert the server rejects it with 401. CORRECT C. Check that the token contains an 'exp' claim and is base64-encoded. D. Assert the token length is greater than 100 characters. RATIONALE: Re-signing with the correct secret and expecting rejection tests signature verification integrity. Option A tests for a vulnerability (alg none); C and D are superficial checks that don't validate tamper resistance.

Q5 DESIGN AND IMPLEMENT SECURE UNIT TESTS USING PYTEST ADVANCED FEATURES

(FIXTURES, PARAMETRIZATION, MOCKING)

A CI pipeline runs bandit -r . and flags a subprocess.call with shell=True.

Which remediation and corresponding test best verifies the fix?

A. Replace with subprocess.run without shell and add a test asserting no shell metacharacters are interpreted. CORRECT B. Add # nosec comment and write a test that the command executes successfully. C. Switch to os.system and test with a benign command. D. Use shlex.quote on arguments and test only with alphanumeric input. RATIONALE: Removing shell=True prevents injection; a test with metacharacters verifies safety. Nosec ignores the risk; os.system is also unsafe; shlex.quote without testing special chars is incomplete.

Q6 IDENTIFY AND VERIFY COMMON VULNERABILITIES (INJECTION, BROKEN AUTH, XSS) IN

PYTHON APIS VIA AUTOMATED TESTS

You are testing a GraphQL API for authorization flaws. The schema allows

querying user(id: ID!) and returns sensitive fields. Which test most effectively

detects broken object-level authorization (BOLA)?

A. Query for your own user ID and assert fields are returned. B. Query for another user's ID using your token and assert access is denied. CORRECT C. Send an introspection query to list all types. D. Test that the API returns 200 for a valid query. RATIONALE: BOLA occurs when a user can access another user's data by changing the ID. Testing cross-user access with your token directly verifies the flaw. A and D only test normal operation; C checks introspection, not authorization.

Q7 IDENTIFY AND VERIFY COMMON VULNERABILITIES (INJECTION, BROKEN AUTH, XSS) IN

PYTHON APIS VIA AUTOMATED TESTS

A test uses unittest.mock.patch to replace requests.post and assert a security

header is set. However, the test passes even when the header is missing. What is

the most likely cause?

A. The mock is not asserting the call arguments correctly. B. The test is patching the wrong module path. C. The header is added after the mock call. D. The test uses assert_called_once() without checking call args. CORRECT RATIONALE: assert_called_once() only checks the call count, not arguments. To verify headers, you must inspect call_args. The other options could be issues but D directly explains the false positive.

Q8 IDENTIFY AND VERIFY COMMON VULNERABILITIES (INJECTION, BROKEN AUTH, XSS) IN

PYTHON APIS VIA AUTOMATED TESTS

When fuzzing a Python API endpoint with hypothesis, which strategy best

uncovers a denial-of-service vulnerability via resource exhaustion?

A. Generate random JSON payloads with large arrays and measure response time. CORRECT B. Send a single request with a very long string. C. Use @given(st.text()) and assert the endpoint returns 200. D. Mock the database and test with empty input. RATIONALE: Large arrays can trigger algorithmic complexity or memory issues; measuring response time detects DoS. A single long string may not stress; C only checks status; D bypasses real resource usage.

Q11 INTEGRATE SAST/DAST TOOLS AND FUZZING INTO CI/CD PIPELINES TO DETECT

SECURITY REGRESSIONS

A pytest suite uses a session-scoped fixture that mutates a shared in-memory

cache. When run with pytest -n auto (pytest-xdist), tests intermittently fail with

stale data that never appears under serial execution. Which mechanism best

explains this and the correct remediation?

A. Session-scoped fixtures are re-instantiated per worker; the fix is to promote the fixture to module scope so each test module gets a fresh cache. B. Each xdist worker runs in a separate process, so the 'shared' cache is actually per-worker; the fix is to make the fixture function-scoped or use a truly shared external store. CORRECT C. pytest-xdist serializes fixture setup via a global lock, so the failures stem from a race on teardown ordering; the fix is to add autouse=True. D. The failures are caused by pytest caching bytecode; the fix is to disable the cache provider with -p no:cacheprovider. RATIONALE: pytest-xdist distributes tests across separate worker processes, so an in-memory session fixture is duplicated per worker and cannot provide cross-test shared state; making it function-scoped or using an external shared store restores determinism. The other options misattribute the cause to scope promotion, teardown locking, or bytecode caching, none of which address process isolation.

Q12 INTEGRATE SAST/DAST TOOLS AND FUZZING INTO CI/CD PIPELINES TO DETECT

SECURITY REGRESSIONS

An API returns a JWT signed with RS256. A unit test must verify that tampering

with the payload is detected. Which assertion most rigorously validates signature

integrity rather than merely parsing claims?

A. Assert that jwt.decode(token, options={'verify_signature': False})['sub'] equals the expected subject. B. Assert that re-encoding the decoded header and payload with the server's public key reproduces the original token. C. Assert that jwt.decode(token, public_key, algorithms=['RS256']) raises InvalidSignatureError after a single byte of the payload is flipped. CORRECT D. Assert that the token's exp claim is in the future and the algorithm header equals 'RS256'. RATIONALE: Only verifying the signature against the public key and confirming that a payload mutation triggers InvalidSignatureError actually tests cryptographic integrity. Options A and D bypass signature verification or only inspect claims, while B misuses the public key (signing requires the private key), so it cannot reproduce a valid token.

Q13 INTEGRATE SAST/DAST TOOLS AND FUZZING INTO CI/CD PIPELINES TO DETECT

SECURITY REGRESSIONS

A test uses unittest.mock.patch to replace requests.get inside a module under

test. The test passes, yet the real function is still called in production. Which

patching error most likely explains this?

A. The patch target was requests.get globally instead of the name as imported into the module under test (e.g., mymodule.requests.get). CORRECT B. patch cannot mock functions from third-party libraries; only patch.object works on external modules. C. The mock was created with spec=True, which disables call interception. D. The test lacked autouse=True, so the patch was never applied during the call. RATIONALE: patch replaces the name where it is looked up; patching requests.get globally does not affect a module that bound the reference via from requests import get or that resolves the attribute through its own namespace. The other options misstate mock capabilities (B), confuse spec behavior (C), or misunderstand autouse scoping (D).

Q16 WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK 48 PRACTICE TESTS

A CI pipeline runs pytest --cov and enforces --cov-fail-under=90. A developer

adds tests that execute many lines via fixtures but assert nothing. Coverage rises

to 95% while a critical authorization bug ships. Which concept best explains this

failure of the quality gate?

A. Line coverage instruments only statements, so branch coverage would have caught the bug. B. Coverage measures execution, not assertion strength; mutation testing would reveal that the tests fail to detect the defect. CORRECT C. The threshold should be raised to 100% to guarantee correctness. D. pytest-cov under-reports assertions, so the metric is unreliable by design. RATIONALE: Coverage quantifies which code executed, not whether outputs were verified, so assertion-free tests inflate it without detecting defects; mutation testing measures the suite's defect-detection power. Branch coverage (A) can help but does not address missing assertions, 100% (C) is no guarantee, and D misstates what pytest-cov measures.

Q17 WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK 48 PRACTICE TESTS

An OAuth 2.0 protected API returns 200 for a request carrying an access token

whose scope lacks the required write:orders. Which test assertion correctly

captures the expected authorization behavior?

A. Assert status == 200 because a valid token was presented. B. Assert status == 401 because authentication failed. C. Assert status == 403 because the token is authenticated but insufficiently scoped. CORRECT D. Assert status == 400 because the request body is malformed. RATIONALE: A valid but under-scoped token is an authorization failure, correctly mapped to 403 Forbidden; 401 denotes authentication failure and 400 denotes a malformed request. Accepting 200 (A) would encode a privilege-escalation vulnerability into the test oracle.

Q18 WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK 48 PRACTICE TESTS

A test suite uses pytest.raises(ValueError) around a function that internally

catches and re-raises a ValueError from a dependency. The test passes even

when the dependency is mocked to raise TypeError. What is the most likely

cause?

A. pytest.raises matches subclasses, and TypeError is a subclass of ValueError. B. The mock's side_effect was set to a callable that swallows the exception before it propagates. C. pytest.raises suppresses all exceptions unless match is provided. D. The function under test wraps any exception in ValueError, masking the injected TypeError. CORRECT RATIONALE: If the function under test catches broad exceptions and re-raises ValueError, the injected TypeError is masked and the assertion passes for the wrong reason. TypeError is not a subclass of ValueError (A), side_effect callables propagate normally (B), and pytest.raises does not suppress without match (C).

Q19 WGU D385 PYTEST & SECURITY UNIT TESTING WORKBOOK 48 PRACTICE TESTS

A security test asserts that a CSRF-protected endpoint rejects requests lacking a

valid token. The test passes, but the endpoint remains vulnerable because the

token is validated only when a specific header is present. Which test-design flaw

best explains the false assurance?

A. The test omitted negative cases where the header is present but the token is invalid or absent. CORRECT B. The test used requests instead of httpx, which cannot test CSRF. C. The test should have asserted a 200 response to confirm the endpoint works. D. The test should have disabled TLS verification to expose the vulnerability. RATIONALE: By only exercising the no-header path, the suite never checks the branch where the header exists but the token is missing or forged, which is exactly the vulnerable condition. The HTTP client choice (B), asserting success (C), and disabling TLS (D) are irrelevant to CSRF token validation logic.

Q22 PYTHON SECURITY

A Flask API endpoint returns 200 for GET /users/ but leaks whether an ID

exists via differing response bodies. Which test design best detects this

enumeration vulnerability under a security-focused unit test?

A. Assert status code equals 200 for a known ID and 404 for an unknown ID B. Assert that response time, status, and body schema are indistinguishable for existing and non-existing IDs CORRECT C. Assert that the endpoint rejects SQL metacharacters in the ID path parameter D. Assert that the Content-Type header is application/json for all requests RATIONALE: User enumeration is detected by verifying that responses for valid and invalid identifiers are indistinguishable across timing, status, and body shape. Checking only 200 vs 404 or content type ignores the leak, and SQL metacharacter rejection tests injection, not enumeration.

Q23 PYTHON SECURITY

In a pytest suite, conftest.py at the project root defines a fixture api_client. A

subdirectory tests/security/conftest.py defines a fixture with the same name. A

test in tests/security/ requests api_client. Which fixture is injected, and why

does this matter for security test isolation?

A. The root fixture, because conftest resolution is global B. The security fixture, because the nearest conftest.py takes precedence CORRECT C. Both fixtures, merged by pytest at runtime D. Neither; pytest raises a duplicate fixture error RATIONALE: Pytest resolves fixtures from the closest conftest.py in the directory hierarchy, so the security-local fixture overrides the root one. This matters because a security conftest can inject hardened clients or mocks without affecting unrelated tests. Duplicate names across conftest files are not errors; the nearer definition wins.

Q24 PYTHON SECURITY

A test asserts hashlib.sha256(b'password').hexdigest() equals a hardcoded value

to verify password hashing. A reviewer flags this as a security anti-pattern. Which

replacement best reflects current password-storage best practice in a unit test?

A. Assert the hash equals bcrypt.hashpw output with a fixed salt B. Assert that bcrypt.checkpw returns True for the correct password and False otherwise, without asserting the digest CORRECT C. Assert the SHA-256 digest length is 64 characters D. Assert the hash changes when the password changes RATIONALE: Modern password storage requires salted, adaptive hashing (bcrypt/argon2), and tests should verify verification behavior rather than fixed digests. Asserting a fixed bcrypt salt or SHA-256 properties does not validate the security property. The checkpw round-trip test captures correctness without brittle or insecure assertions.

Q25 PYTHON SECURITY

A pytest test uses unittest.mock.patch to replace requests.get and asserts a

downstream function calls it. The test passes, but in production the function calls

requests.Session().get. What is the most precise correction?

A. Patch requests.get with autospec=True B. Patch requests.Session.get instead of requests.get CORRECT C. Use monkeypatch.setattr(requests, 'get', ...) in a fixture D. Assert the call count using mock.call_count RATIONALE: The test mocks the wrong attribute; production uses Session.get, so patching requests.get leaves the real call unmocked. autospec on requests.get still patches the wrong symbol, monkeypatch has the same target problem, and call_count assertions do not fix the target.

Q28 API TESTING & VULNERABILITY VERIFICATION 2026

A security unit test verifies an API rejects requests with a missing Authorization

header. The endpoint is also reachable via a /health path that intentionally allows

anonymous access. Which test structure best prevents a false sense of coverage?

A. Parametrize over all endpoints and assert 401 for each B. Parametrize over protected endpoints asserting 401 and separately assert /health returns 200 without credentials CORRECT C. Assert only that /health returns 200 D. Assert that the 401 response body does not reveal server version RATIONALE: Correct coverage distinguishes protected endpoints (401 without credentials) from intentionally public ones (/health 200), avoiding both false positives and false negatives. Asserting 401 for all endpoints would incorrectly fail /health, and testing only /health or response body hygiene misses the auth boundary.

Q29 API TESTING & VULNERABILITY VERIFICATION 2026

A CI pipeline runs pytest --cov=app --cov-fail-under=90. A developer adds many

trivial getter tests to raise coverage. Which metric best complements coverage to

detect this gaming and improve security test quality?

A. Line coverage percentage B. Branch coverage percentage C. Mutation score from a mutation testing tool CORRECT D. Number of assertions per test RATIONALE: Mutation testing introduces faults and measures whether tests detect them, exposing tests that execute code without meaningful assertions. Line and branch coverage can be inflated by trivial tests, and assertion count is a weak proxy for test strength.

Q30 API TESTING & VULNERABILITY VERIFICATION 2026

A pytest test for an input-validation function uses pytest.raises(ValueError) with

no match argument. A reviewer notes the test could pass even if the wrong

ValueError is raised. Which refinement best strengthens the assertion?

A. Add match= with a regex matching the expected message CORRECT B. Wrap the call in a try/except and assert the exception type C. Use pytest.warns instead of pytest.raises D. Assert the function returns None on invalid input RATIONALE: Using match= constrains the exception to the expected message, distinguishing the intended error from unrelated ValueErrors. try/except replicates the unconstrained check, pytest.warns targets warnings not exceptions, and asserting None changes the expected behavior.

Q31 FOUNDATIONS OF SOFTWARE SECURITY & PYTHON TESTING

In a pytest suite, a test module defines a fixture db with scope='module'. A

second test module requests db via a conftest.py fixture that yields a transaction

and rolls back. Which statement best characterizes the fixture lifecycle and

isolation guarantee?

A. The conftest fixture is instantiated once per session, so rollback occurs only after all modules finish, leaking state across modules. B. The conftest fixture wraps the module-scoped db; its transaction is created per test function, preserving function-level isolation while reusing the connection. CORRECT C. Because db is module-scoped, the conftest fixture must also be module-scoped; pytest raises a ScopeMismatch error otherwise. D. The conftest fixture overrides db and forces function scope, silently ignoring the module scope declaration. RATIONALE: A function-scoped fixture may depend on a broader-scoped fixture; the narrower scope controls setup/teardown frequency, so the transaction is per-test while the connection is reused. Option C is wrong because pytest allows narrower fixtures to depend on broader ones, not the reverse. A and D misstate scope resolution rules.

Q34 FOUNDATIONS OF SOFTWARE SECURITY & PYTHON TESTING

A test asserts that a password hashing function uses bcrypt with cost factor 12.

Which assertion strategy is most robust against implementation changes while

still verifying the security property?

A. Assert the output starts with $2b$12$ and that two calls with the same password differ. CORRECT B. Assert the output length is exactly 60 characters and contains a salt. C. Assert the function calls bcrypt.hashpw exactly once using a mock. D. Assert the output equals a precomputed hash of the password. RATIONALE: Checking the bcrypt prefix encodes algorithm and cost, and differing outputs verify salting-both are security properties. B is weak (length alone), C couples to implementation, and D breaks with salting.

Q35 FOUNDATIONS OF SOFTWARE SECURITY & PYTHON TESTING

In property-based testing with Hypothesis, which strategy best detects an integer

overflow vulnerability in a deserialization function?

A. st.integers(min_value=-(2**63), max_value=2**63-1) with a check that round-trip equality holds. CORRECT B. st.integers() with a check that no exception is raised. C. st.text() with a check that the function returns a string. D. st.floats(allow_nan=False) with a check that the result is finite. RATIONALE: Boundary integers at 64-bit limits expose overflow/underflow during serialization round-trips. B lacks bounds, C tests wrong type, and D targets floats, not integer overflow.

Q36 APPLIED SOFTWARE SECURITY & PYTHON TESTING

A JWT authentication middleware is tested. Which pytest assertion best verifies

that the alg=none attack is mitigated?

A. Send a token with header {"alg":"none"} and no signature; assert 401 Unauthorized. CORRECT B. Send a token signed with HS256 using the correct secret; assert 200 OK. C. Send an expired token; assert 401 Unauthorized. D. Send a token with an invalid signature; assert 401 Unauthorized. RATIONALE: The alg=none attack exploits libraries accepting unsigned tokens; asserting rejection specifically validates mitigation. B tests valid auth, C tests expiry, and D tests signature verification-none isolate the none-algorithm bypass.

Q37 APPLIED SOFTWARE SECURITY & PYTHON TESTING

Which pytest plugin configuration most effectively prevents accidental network

calls during unit tests while permitting explicit integration tests?

A. Use pytest-socket with --disable-socket and a @pytest.mark.enable_socket marker on integration tests. CORRECT B. Use pytest-httpserver to stub all external endpoints globally. C. Use responses to mock requests, and rely on developers to register mocks. D. Use pytest-xdist to parallelize tests so network calls time out faster. RATIONALE: pytest-socket blocks sockets by default and allows opt-in via marker, enforcing isolation. B requires stubbing every endpoint, C is opt-in and leaky, and D does not block network access.