Docsity

WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging,, Exams of Computer Security

Toggle sidebar
bg1
WGU D385 Task 1 Performance Assessment Guide Software
Security & Testing Python Logging, Assertions, Static Code
Analysis & Testing 2026
This exam assesses advanced competency in Python software security and testing, covering secure logging
practices, assertion semantics under optimized bytecode, static analysis tooling (Bandit, Semgrep, mypy, pylint),
and the design of effective unit, property-based, and integration tests. It emphasizes the ability to reason about
subtle security vulnerabilities, test oracle quality, and the interaction between runtime checks and static
verification. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that
explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the
major content areas of the course. Targeted learning outcomes include: Configure Python logging to prevent
sensitive data leakage and injection attacks while preserving auditability.; Analyze the behavior of assert
statements under -O optimization and select appropriate runtime validation strategies.; Interpret and integrate
outputs from static code analysis tools (Bandit, Semgrep, mypy) into a secure SDLC.; Design property-based and
mutation-tested suites that expose real faults rather than tautological or brittle tests.. Every item has been
reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and
self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a
structured practice tool during the unit - the rationales double as concise teaching notes. The recommended
writing time is 3 hours, with a passing score of 80% (40/50). Aligned with Aligned with US regional accreditation
Section 1: General (Questions 1-50)
1A logging configuration uses logging.basicConfig(format='%(asctime)s
%(levelname)s %(message)s') and logs a user-supplied username directly. An
attacker sets the username to a string containing a newline followed by a forged
log entry. Which mitigation most directly prevents log injection while preserving
structured auditability?
A) Set the logging level to WARNING to reduce the attack surface.
B) Use a JSON formatter that serializes the message field and escapes control
characters.
C) Wrap the log call in a try/except to catch injection exceptions.
D) Encode the username with base64 before logging.
Answer: B
Rationale: Structured JSON logging serializes and escapes newlines/control
characters, neutralizing forged entries while keeping fields queryable. Level changes
and exception handling do not sanitize content, and base64 obscures but does not
structurally separate attacker-controlled data from log metadata.
2A developer writes: assert user.is_admin, 'denied' to guard a privileged function,
then deploys with PYTHONOPTIMIZE=1. Which statement best characterizes
the resulting security posture?
A) The assertion still raises AssertionError because the message is present.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, and more Exams Computer Security in PDF only on Docsity!

WGU D385 Task 1 Performance Assessment Guide Software

Security & Testing Python Logging, Assertions, Static Code

Analysis & Testing 2026

This exam assesses advanced competency in Python software security and testing, covering secure logging practices, assertion semantics under optimized bytecode, static analysis tooling (Bandit, Semgrep, mypy, pylint), and the design of effective unit, property-based, and integration tests. It emphasizes the ability to reason about subtle security vulnerabilities, test oracle quality, and the interaction between runtime checks and static verification. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the major content areas of the course. Targeted learning outcomes include: Configure Python logging to prevent sensitive data leakage and injection attacks while preserving auditability.; Analyze the behavior of assert statements under -O optimization and select appropriate runtime validation strategies.; Interpret and integrate outputs from static code analysis tools (Bandit, Semgrep, mypy) into a secure SDLC.; Design property-based and mutation-tested suites that expose real faults rather than tautological or brittle tests.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes. The recommended writing time is 3 hours, with a passing score of 80% (40/50). Aligned with Aligned with US regional accreditation

Section 1: General (Questions 1-50)

1 A logging configuration uses logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') and logs a user-supplied username directly. An attacker sets the username to a string containing a newline followed by a forged log entry. Which mitigation most directly prevents log injection while preserving structured auditability?

A) Set the logging level to WARNING to reduce the attack surface. B) Use a JSON formatter that serializes the message field and escapes control characters.

C) Wrap the log call in a try/except to catch injection exceptions. D) Encode the username with base64 before logging.

Answer: B Rationale: Structured JSON logging serializes and escapes newlines/control characters, neutralizing forged entries while keeping fields queryable. Level changes and exception handling do not sanitize content, and base64 obscures but does not structurally separate attacker-controlled data from log metadata.

2 A developer writes: assert user.is_admin, 'denied' to guard a privileged function, then deploys with PYTHONOPTIMIZE=1. Which statement best characterizes the resulting security posture?

A) The assertion still raises AssertionError because the message is present.

B) The assertion is stripped, so the guard never executes and the function becomes unconditionally accessible.

C) The assertion is converted to a warning but execution continues. D) PYTHONOPTIMIZE only affects docstrings, so the assertion is unaffected.

Answer: B Rationale: Under -O/PYTHONOPTIMIZE, the compiler removes assert statements entirely, eliminating the guard and its message. Assertions must never enforce security; explicit if/raise or authorization decorators are required. The other options misstate optimization semantics.

3 Bandit reports B301 (pickle) on a function that deserializes data from a trusted internal queue, but the queue is fed by a webhook that accepts unauthenticated JSON. Which action best reflects correct triage?

A) Suppress B301 with # nosec because the queue is internal. B) Treat the finding as a true positive and replace pickle with a safe format (e.g., JSON) plus schema validation.

C) Downgrade severity to LOW because the queue is internal. D) Add a try/except around pickle.loads to catch malicious payloads.

Answer: B Rationale: Taint flows from an unauthenticated webhook through the queue to pickle.loads, making the finding a true positive with potential RCE. Suppression or severity downgrade ignores the taint path, and try/except cannot prevent code execution during deserialization.

4 A test suite achieves 100% line coverage yet misses a bug where a function returns None for empty input. Which testing technique would most likely expose this defect?

A) Increasing line coverage to 100% on all branches. B) Adding property-based tests that assert invariants across generated inputs, including empty sequences.

C) Running the suite under pytest -x to stop on first failure. D) Adding more assertions inside the function under test.

Answer: B Rationale: Line coverage does not guarantee oracle quality or input diversity; property-based testing generates edge cases like empty inputs and checks invariants, exposing the None return. Branch coverage may still miss it, -x only changes failure handling, and internal assertions do not create external test oracles.

Rationale: Patching out the module under test prevents its mutated code from executing, yielding zero kills regardless of test quality. Equivalent mutants are possible but unlikely across an entire module, and mutation testing does not require full branch coverage to operate.

8 A logging handler writes to a file with mode='w' on every application start. An incident review finds that audit logs from the previous run are missing. Which change best preserves audit integrity?

A) Switch to mode='a' and rotate files with a size-based handler. B) Increase the log level to CRITICAL to reduce writes. C) Buffer logs in memory and flush at shutdown. D) Write logs to stdout and rely on the shell to redirect.

Answer: A Rationale: Mode 'w' truncates the file at each start, destroying prior audit records; append mode with rotation preserves history while controlling size. Higher levels, in-memory buffering, and stdout redirection do not guarantee durable, tamper-resistant audit trails.

9 A function uses yaml.load(data, Loader=yaml.FullLoader) on untrusted input. Static analysis flags it, but the developer argues FullLoader is safe. Which statement is most accurate?

A) FullLoader is safe because it disables all Python object construction. B) FullLoader is safer than UnsafeLoader but still permits some complex tags and should be replaced with safe_load for untrusted data.

C) FullLoader is identical to UnsafeLoader in all respects. D) yaml.load is safe if the input is UTF-8.

Answer: B Rationale: FullLoader avoids arbitrary code execution but still supports a broad tag set and is not intended for untrusted input; safe_load restricts to basic types. The other options overstate or misstate the differences between loaders.

10 A CI pipeline runs bandit -r. -ll and exits 0 despite a HIGH severity finding because the finding is in a test file excluded by default. Which configuration change ensures security findings in test code are also reviewed?

A) Remove the -ll flag to include all severities. B) Add --exclude tests to the command. C) Override the default exclusion with --include or remove tests from the excluded set.

D) Run bandit with -s B101 to skip assert checks.

Answer: C Rationale: Bandit's default exclusions include common test directories; to scan them, the exclusion set must be overridden or removed. -ll only filters severity, --exclude adds exclusions, and -s skips specific tests rather than including test files.

11 A developer writes assert user.is_admin, "denied" inside a request handler that is deployed with python -O. Which security property does this deployment most directly violate?

A) Confidentiality of the assertion message in logs B) Integrity of the authorization check, because assertions are stripped under -O C) Availability, because -O disables exception handling D) Non-repudiation, because assert writes no audit record

Answer: B Rationale: CPython removes assert statements when debug is false (e.g., -O/-OO), so an authorization guard implemented as an assertion silently disappears, breaking the integrity of the access-control decision. Assertions are for internal invariants, not security enforcement; the other options misattribute the failure mode to logging, availability, or auditability.

12 A test suite passes locally but fails in CI only when a test that mutates a module-level dict runs before another test. Which pytest mechanism most directly eliminates this class of inter-test coupling?

A) pytest.mark.parametrize B) A session-scoped fixture that shares the dict C) pytest-randomly with a fixed seed D) An autouse function-scoped fixture that restores the dict

Answer: D Rationale: An autouse function-scoped fixture that snapshots and restores the module-level dict isolates state between tests, removing order dependence. Parametrization changes inputs, session-scoped fixtures worsen sharing, and a fixed random seed only makes the order deterministic-not independent.

13 Bandit reports B608: hardcoded_sql_expressions for cur.execute(f"SELECT * FROM t WHERE id={uid}"). Which remediation most completely removes the vulnerability class rather than masking the finding?

A) Cast uid to int before interpolation B) Add # nosec with a justification comment

16 A team wants static analysis to fail CI when cyclomatic complexity exceeds 10 but to ignore generated migration files. Which configuration approach best satisfies both requirements in a modern Python project?

A) Run radon with --total-average and parse the exit code B) Configure a linter (e.g., Ruff C901 with max-complexity) and exclude migrations via extend-exclude

C) Add # noqa: C901 to every migration file D) Use mypy --strict with per-module overrides

Answer: B Rationale: Ruff's C901 rule with max-complexity and an extend-exclude glob enforces a complexity threshold while skipping generated code in one config. Radon's average metric does not gate per-function complexity, blanket noqa is unmaintainable, and mypy does not measure complexity.

17 A fuzz target wraps a JSON parser and crashes only when given deeply nested arrays, exhausting the C stack. Which mitigation most directly addresses this denial-of-service class?

A) Increase the fuzzer's timeout B) Run the parser in a thread with a larger stack C) Enforce a maximum nesting depth and reject inputs exceeding it D) Catch RecursionError and return None

Answer: C Rationale: Bounding nesting depth constrains resource consumption at the input boundary, preventing stack exhaustion. Raising timeouts or stack size only delays the crash, and catching RecursionError is unreliable once the C stack is exhausted.

18 A CI pipeline runs coverage run -m pytest then coverage report --fail-under=90. A module with only if TYPE_CHECKING: imports reports uncovered lines. Which action is most appropriate?

A) Lower the threshold to 80% B) Add # pragma: no cover to type-checking blocks and enable coverage's branch analysis

C) Delete the type-checking imports D) Run tests with -O to skip the block

Answer: B Rationale: Type-checking-only blocks never execute at runtime, so # pragma: no cover (with branch coverage enabled) accurately excludes them without masking

real gaps. Lowering the bar, deleting imports, or running with -O degrades type safety or coverage fidelity.

19 A developer uses logging.info(f"user={user}") in a hot loop and disables INFO in production. Which combination of changes best improves both performance and security?

A) Switch to %-style lazy formatting and log a hashed user identifier B) Use logging.debug with f-strings C) Buffer messages in a list and flush at exit D) Set the logger level to CRITICAL and remove the log call

Answer: A Rationale: Lazy %-style formatting defers string construction until the record is emitted, avoiding cost when disabled, while hashing the identifier prevents PII leakage. Debug f-strings still format eagerly, buffering risks data loss, and removing logs destroys observability.

20 A property-based test uses Hypothesis to validate sort(xs). Which strategy most effectively uncovers subtle ordering bugs while controlling runtime?

A) Generate only lists of unique integers B) Use st.lists(st.integers()) with @settings(max_examples=5) C) Use st.lists(st.integers()) with @settings(max_examples=1000, deadline=None) and assert sortedness plus permutation equivalence

D) Generate random floats and compare with ==

Answer: C Rationale: Broad integer lists with many examples and a deadline disabled exercise edge cases, while asserting both sortedness and permutation equivalence catches reordering or duplication bugs. Restricting to unique ints, too few examples, or float equality weakens the oracle.

21 A CI pipeline runs pytest --cov=src --cov-fail-under=90. After adding a new module, coverage drops to 87% and the build fails. Which pytest-cov configuration change most precisely restores the build while still enforcing 90% coverage only on the newly added module?

A) Add --cov-fail-under=0 and rely on a separate CI job for the new module. B) Use --cov=src/new_module --cov-fail-under=90 alongside the existing global threshold.

C) Set [tool.coverage.run] source = ["src/new_module"] in pyproject.toml.

C) Defer handler configuration to the application entry point and let pytest manage the root logger.

D) Set logging.disable(logging.CRITICAL) in the module.

Answer: C Rationale: pytest's caplog fixture installs its own handler on the root logger; libraries that configure handlers at import interfere with propagation. Deferring configuration to the application entry point preserves library hygiene and enables capture.

25 A team wants deterministic tests for code that calls datetime.now(). Which approach best supports testability without monkeypatching the standard library globally?

A) Freeze time with freezegun in every test module via a conftest autouse fixture. B) Inject a clock callable (e.g., clock=datetime.now) as a default parameter or dependency.

C) Patch datetime.datetime with unittest.mock.patch in each test. D) Set the system clock in CI to a fixed date.

Answer: B Rationale: Dependency injection of a clock is the most surgical, side-effect-free approach and aligns with testable design principles. Freezegun and global patching work but are broader and can mask unrelated time usage; altering the system clock is non-portable.

26 Which assertion strategy best balances coverage and maintainability when testing a function that returns a large nested dictionary whose schema is stable but values vary?

A) Assert full equality against a hard-coded golden dict. B) Assert only that the return value is a dict. C) Assert on a curated subset of keys plus type/shape constraints. D) Assert that the dict is non-empty and has more than three keys.

Answer: C Rationale: Targeted assertions on stable keys and shape reduce brittleness while still catching meaningful regressions. Full equality (A) is fragile, and B/D are too weak to detect real defects.

27 Bandit reports B301 (pickle) on a deserialization path. Which change most directly preserves functionality while eliminating the vulnerability class?

A) Wrap pickle.loads in a try/except and log failures. B) Replace pickle with a safe format such as JSON or a schema-validated parser.

C) Restrict pickle input length to a maximum size. D) Run the deserialization inside a subprocess with reduced privileges.

Answer: B Rationale: Pickle executes arbitrary code during unpickling; the only robust fix is to avoid it for untrusted data and use a safe serialization format. Length limits, exception handling, and sandboxing do not remove the code-execution primitive.

28 A property-based test uses Hypothesis to validate a sort function. Which property most strongly validates correctness independent of implementation details?

A) The output list has the same length as the input. B) The output is sorted and is a permutation of the input. C) The first element is the minimum of the input. D) The output contains no duplicate values.

Answer: B Rationale: A correct sort must both order elements and preserve the multiset of inputs, making B the strongest invariant. Length, minimum, and uniqueness checks are necessary but not sufficient and can pass on incorrect implementations.

29 In a security review, a developer proposes assert user.is_admin to gate an admin action in production code. Why is this considered an anti-pattern?

A) Assertions are slower than if-statements at runtime. B) Assertions can be stripped when Python runs with -O, silently disabling the check.

C) Assertions cannot reference object attributes. D) Assertions raise SystemExit instead of AssertionError.

Answer: B Rationale: Python's -O flag removes assert statements, so security-relevant checks may vanish in optimized deployments. Assertions are for internal invariants; authorization must use explicit conditionals and proper exceptions.

30 A test suite uses unittest.mock.patch to stub a network client but tests intermittently fail when run in parallel. Which practice most improves reliability?

A) Increase the mock's side_effect to raise on any unexpected call. B) Use patch as a context manager or decorator scoped to each test rather than module-level patching.

C) Set autospec=True on every patch call.

Rationale: -O removes assert statements entirely, so using asserts for security validation is unsafe; the check disappears at runtime and pickle can execute arbitrary code. Asserts are not downgraded (B), __debug__ blocks do not exempt module-level asserts (C), and pickle has no built-in opcode whitelist (D).

33 A CI pipeline runs bandit -r src/ and reports B301 (pickle) as LOW severity. The team suppresses it with # nosec. Which reasoning most correctly evaluates this decision from a secure-SDLC standpoint?

A) Suppression is acceptable because LOW severity findings are informational and never require triage.

B) Suppression is risky: severity reflects likelihood/impact heuristics, not exploitability in context; untrusted pickle input is an RCE vector regardless of the tool's default severity.

C) Suppression is required because Bandit's B301 is a known false positive whenever pickle is imported.

D) Suppression is fine only if the code also passes mypy --strict, because type checking proves the payload is trusted.

Answer: B Rationale: Static analyzer severity is a heuristic, not a contextual risk judgment; deserializing untrusted pickle is remote code execution irrespective of Bandit's LOW label, so blanket # nosec without justification is unsafe. LOW findings still require triage (A), B301 is not inherently a false positive (C), and type checking does not establish data trustworthiness (D).

34 A pytest suite achieves 95% line coverage but misses a critical branch where an except ValueError handler is never executed. Which metric and tool combination most directly exposes this gap?

A) Line coverage via coverage.py; the handler lines are counted as covered because they are syntactically present.

B) Branch coverage via coverage.py --branch; it flags the unexecuted handler path as a partial branch.

C) Mutation testing via mutmut; it measures whether tests detect injected faults, which correlates directly with handler execution.

D) Cyclomatic complexity via radon; high complexity in the try/except guarantees the handler is untested.

Answer: B Rationale: Branch coverage tracks whether both outcomes of conditional constructs (including exception paths) are exercised, exposing the never-taken handler. Line

coverage can mark the handler lines as present without execution (A), mutation testing detects fault sensitivity but not branch execution per se (C), and complexity metrics measure structure, not test execution (D).

35 A developer writes logging.info(f"user={user} token={token}"). A security review flags this. Which remediation best follows current OWASP logging guidance?

A) Switch to logging.info("user=%s token=%s", user, token) to defer formatting and improve performance.

B) Remove the token from the message and log only non-sensitive identifiers; use lazy %s formatting for permitted fields.

C) Raise the log level to DEBUG so the token is only emitted in development environments.

D) Hash the token with MD5 before logging so the value is not directly readable.

Answer: B Rationale: OWASP guidance requires excluding sensitive data from logs; deferring formatting (A) addresses performance, not disclosure. DEBUG does not prevent leakage in production (C), and MD5 of a token is reversible/guessable and still sensitive (D). The correct fix removes the secret and uses lazy formatting for allowed fields.

36 A pytest fixture uses yield to open a DB connection and roll back after each test. A test that spawns a thread performing DB writes causes flaky teardown. Which fixture design most robustly resolves this?

A) Convert the fixture to a module-scoped yield fixture to reduce setup frequency.

B) Add autouse=True so the fixture runs for every test including thread-spawned ones.

C) Ensure the fixture joins all spawned threads before yielding control back, using a factory that tracks and terminates threads in teardown.

D) Replace yield with return and rely on addfinalizer to run rollback after the test.

Answer: C Rationale: Teardown ordering with concurrent threads requires deterministic synchronization: the fixture must join/stop threads before rollback so no writes race the cleanup. Module scope increases shared state (A), autouse does not synchronize threads (B), and addfinalizer has similar ordering issues without joining (D).

Answer: B Rationale: Asserts document internal invariants and are stripped under optimization, making them unsuitable for validating public inputs; explicit exceptions enforce contracts in all modes. Performance (A) is not the core issue, asserts can be logged indirectly (C), and asserts do accept messages (D).

40 A security test must verify that a function rejects path traversal. Which test design most rigorously validates the control rather than merely the happy path?

A) Assert the function returns the input unchanged for ../etc/passwd. B) Parameterize over encoded variants (..%2f, ..\, null-byte suffixes) and assert each raises or normalizes to a safe path.

C) Mock os.path and assert it was called with the raw input. D) Check that the function's docstring documents traversal handling.

Answer: B Rationale: Rigorous negative testing enumerates encoded and platform-specific traversal variants and asserts rejection or safe normalization, exercising the control across realistic bypasses. Returning input unchanged (A) validates nothing, mocking internals (C) tests implementation not behavior, and docstring checks (D) are not security tests.

41 A service configures logging with a RotatingFileHandler and sets propagate=False on a child logger. A developer then adds a StreamHandler to the root logger. Which statement best describes the resulting output behavior?

A) Records handled by the child logger appear in the file only, because propagate=False suppresses ancestor handlers entirely.

B) Records appear in both the file and the stream because root handlers always receive all records regardless of propagate.

C) Records appear in the file only if the child logger's level is lower than the root logger's effective level.

D) Records are duplicated in the file because the root handler re-emits records already flushed by the child handler.

Answer: A Rationale: propagate=False stops a record from being passed to ancestor loggers' handlers, so only the child's file handler processes it. Root handlers still exist but never receive the record; levels and duplication do not override propagation. Thus B, C, and D misstate the propagation contract.

42 Given assert isinstance(result, dict), f"bad: {result}" under Python's default execution mode, which statement about security and performance is most accurate?

A) The assertion executes unless -O is used, so it is reliable production validation but may leak the value in logs.

B) The assertion is always executed and cannot be disabled, making it safe for input validation in production.

C) The assertion is stripped when Python runs with -O, so it must not be relied upon for security checks.

D) The assertion raises AssertionError only when the message is a non-empty string, otherwise it is ignored.

Answer: C Rationale: With -O or PYTHONOPTIMIZE, assert statements are removed at compile time, so they cannot enforce security invariants in production. The message expression is only evaluated on failure and never changes whether the assert exists. Therefore A, B, and D incorrectly treat assertions as guaranteed runtime guards.

43 A static analyzer reports B301: pickle.loads() on untrusted data. Which remediation most directly eliminates the vulnerability while preserving a serialization workflow?

A) Wrap pickle.loads in a try/except and log the exception before continuing. B) Replace pickle with a restricted unpickler that blocks reduce during loading.

C) Switch to a data-only format such as JSON or a schema-validated parser for untrusted input.

D) Run the deserialization inside a subprocess with lowered privileges and a timeout.

Answer: C Rationale: Pickle deserialization can execute arbitrary code via reduce, so the only robust fix for untrusted input is avoiding pickle in favor of data-only formats like JSON. Exception handling, sandboxing, and restricted unpicklers reduce but do not eliminate the code-execution surface. Hence A, B, and D are insufficient mitigations.

44 A test suite uses unittest.mock.patch on a function imported as from mod import send. After patching mod.send, the test still calls the real function. What is the most likely cause?

coverage. Statement and function coverage can be satisfied without taking both branches, and full path coverage is generally infeasible. Hence A, C, and D do not target the described gap.

47 A security review finds subprocess.Popen(cmd, shell=True) with user-controlled input. Which change most effectively prevents command injection?

A) Escape shell metacharacters in the input using shlex.quote before passing to shell=True.

B) Pass the command as a list with shell=False and validate/allowlist each argument.

C) Redirect stderr to DEVNULL and set a short timeout to limit injection impact. D) Run the process as a non-root user and log all arguments for auditing.

Answer: B Rationale: Using shell=False with an argument list avoids invoking a shell entirely, eliminating shell metacharacter interpretation; allowlisting hardens argument validation. shlex.quote helps but remains error-prone, while timeouts, redirection, and privilege reduction do not remove the injection vector. Thus A, C, and D are weaker or incomplete.

48 A linter flags B105: hardcoded_password_string for a default argument password='admin'. Which remediation best aligns with secure coding and testability?

A) Replace the default with an environment variable lookup and fail fast if unset. B) Suppress the warning with # nosec because defaults are not production secrets.

C) Hash the default password before assignment to avoid plaintext in source. D) Move the default into a test fixture so production code no longer contains it.

Answer: A Rationale: Secrets should be injected from a secure source such as environment variables or a secrets manager, with a fail-fast check when absent. Suppressing the warning, hashing a hardcoded default, or relocating it to fixtures still leaves credentials in code or artifacts. Therefore B, C, and D do not resolve the underlying issue.

49 A team wants tests to fail when a function's behavior changes but its name and signature remain the same. Which testing technique most directly detects this regression?

A) Property-based testing that asserts invariants across randomized inputs. B) Snapshot or golden-master testing that compares serialized outputs to a stored baseline.

C) Mutation testing that alters source code to evaluate test suite strength. D) Load testing that measures throughput under concurrent requests.

Answer: B Rationale: Snapshot/golden-master tests compare current outputs against a stored baseline, so behavior changes surface as diffs even when interfaces are unchanged. Property tests check invariants but may not detect specific output drift, mutation testing evaluates test quality rather than behavior drift, and load testing is unrelated. Hence A, C, and D do not directly detect this regression.

50 A CI pipeline runs bandit -r src and reports B602: subprocess_popen_with_shell_equals_true. Which action best satisfies both security and reproducibility requirements?

A) Add # nosec at the call site and document the exception in the security policy. B) Refactor to subprocess.run(args_list, shell=False, check=True) and pin dependencies.

C) Increase Bandit's severity threshold so the finding no longer appears in reports. D) Move the call into a separate module excluded from Bandit's scan scope.

Answer: B Rationale: Refactoring to shell=False with an argument list removes the injection risk, and pinning dependencies supports reproducibility. Suppressing findings, raising thresholds, or excluding modules hides the vulnerability without fixing it. Therefore A, C, and D fail the stated requirements.