Docsity

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

Toggle sidebar
bg1
Page 1
WGU D385 Task 1 Performance Assessment Guide Software
Security & Testing Python Logging, Assertions, Static Code
Analysis & Testing 2026 - Questions and Answers Already
Graded A+ Premium Exam Tested And Verified
GRADED A+
ABSTRACT
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

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 - Questions and Answers Already

Graded A+ Premium Exam Tested And Verified

GRADED A+

ABSTRACT

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.

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. Use a JSON formatter that serializes the message field and escapes

control characters.

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. The assertion is stripped, so the guard never executes and the function

becomes unconditionally accessible.

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.

5. A Semgrep rule flags f"SELECT * FROM users WHERE name = '{name}'" but

the codebase uses a custom ORM that parameterizes queries before execution. What

is the most rigorous next step?

A. Disable the rule globally to reduce false positives. B. Verify the ORM's parameterization path with a taint-mode Semgrep rule and adjust the rule's sanitizer configuration. C. Convert all queries to string concatenation to satisfy the rule. D. Add # nosemgrep to every flagged line.

Answer: B. Verify the ORM's parameterization path with a taint-mode Semgrep

rule and adjust the rule's sanitizer configuration.

The correct response is to validate the sanitizer behavior and refine the rule using taint mode so it recognizes the ORM's parameterization. Global disabling or blanket suppression hides real issues, and reverting to concatenation would introduce vulnerabilities.

6. A team uses mypy in strict mode but disables --disallow-untyped-defs to speed

adoption. A security-critical function lacks type annotations and accepts Any. Which

risk does this pose to static security analysis?

A. None; mypy still checks all operations on Any values. B. Any propagates and suppresses type-based taint tracking, allowing unsafe flows to pass unchecked. C. mypy will raise a runtime error when Any is used. D. Disabling that flag only affects documentation generation.

Answer: B. Any propagates and suppresses type-based taint tracking, allowing

unsafe flows to pass unchecked.

Any is compatible with all types and effectively disables type checking for those values, which can break taint propagation in type-aware analyzers. The other options misstate mypy's behavior; mypy is static and does not raise runtime errors.

7. A pytest suite uses unittest.mock.patch to replace a payment gateway with a stub

that always returns success. Mutation testing shows zero mutants killed in the

payment module. What is the most likely cause?

A. The mutants are equivalent and cannot be killed. B. The mock removes the real logic from the test path, so mutants in the payment module are never executed. C. Mutation testing requires 100% branch coverage to run. D. The stub returns success, which is the expected behavior.

Answer: B. The mock removes the real logic from the test path, so mutants in the

payment module are never executed.

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. Switch to mode='a' and rotate files with a size-based handler.

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.

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. Integrity of the authorization check, because assertions are stripped

under -O

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. An autouse function-scoped fixture that restores the dict

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 C. Use a parameterized query with a placeholder and pass uid as a bound parameter D. Escape single quotes in uid with a regex

Answer: C. Use a parameterized query with a placeholder and pass uid as a bound

parameter

Parameterized queries separate SQL structure from data, eliminating injection regardless of input shape. Integer casting and regex escaping are fragile allowlist/denylist mitigations, and # nosec suppresses the detector without fixing the flaw.

14. A logger configured with

logging.getLogger('app').setLevel(logging.WARNING) emits records to a handler

with setLevel(logging.DEBUG). A call to app.debug('x') produces no output.

Which explanation is correct?

A. The handler level overrides the logger level, so DEBUG should appear B. The logger's effective level filters the record before it reaches the handler C. DEBUG records require logging.basicConfig(level=DEBUG) regardless of levels D. propagate=False on the root logger discards the record

Answer: B. The logger's effective level filters the record before it reaches the

handler

A logger's level is checked first; if the record's severity is below the logger's effective level, it is discarded before handler-level filtering. Handler levels only refine what the logger already allowed, so options A/C/D misstate the filter ordering.

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. Enforce a maximum nesting depth and reject inputs exceeding it

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 onlyif 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. Add # pragma: no cover to type-checking blocks and enable

coverage's branch analysis

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. Switch to %-style lazy formatting and log a hashed user identifier

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. Use st.lists(st.integers()) with `@settings(max_examples=1000,

deadline=None)` and assert sortedness plus permutation equivalence

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.

23. A test asserts assert result == expected with no message. In pytest, when the

assertion fails on a large dict, which feature most improves diagnostic output

without changing the assertion semantics?

A. Wrap the assertion in try/except and call logging.exception. B. Enable pytest's assertion rewriting (default) and add a descriptive message after a comma. C. Replace with self.assertEqual from unittest for richer diffs. D. Add --tb=no to suppress the traceback and rely on logs.

Answer: B. Enable pytest's assertion rewriting (default) and add a descriptive

message after a comma.

pytest's assertion rewriting produces detailed diffs for complex objects automatically; adding a message supplements context. Option A bypasses rewriting, C loses pytest's introspection, and D hides diagnostics.

24. A module uses logging.getLogger(__name__) and configures handlers at import

time. Under pytest, log records from the module are not captured in caplog. Which

design change most reliably enables capture?

A. Call logging.basicConfig(level=logging.DEBUG) at module top. B. Add a FileHandler in the module to persist logs. 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. Defer handler configuration to the application entry point and let

pytest manage the root logger.

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. Inject a clock callable (e.g., clock=datetime.now) as a default

parameter or dependency.

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. Assert on a curated subset of keys plus type/shape constraints.

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. Replace pickle with a safe format such as JSON or a schema-validated

parser.

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.

31. A team uses logging.getLogger(__name__) throughout a package but configures

handlers only in main.py via basicConfig(). A worker process imports a

submodule directly and emits logs that never appear. Which root cause best explains

the missing output?

A. basicConfig is idempotent and silently no-ops once any handler exists on the root logger; the submodule's import order triggered an earlier no-op configuration. B. Child loggers created with __name__ do not propagate records to the root logger unless propagate=True is explicitly set on each child. C. Logger levels default to WARNING, so INFO/DEBUG records from the submodule are filtered before reaching the root handler. D. The submodule's logger name lacks a dot, so Python treats it as a top-level logger disconnected from the root hierarchy.

Answer: A. basicConfig is idempotent and silently no-ops once any handler exists

on the root logger; the submodule's import order triggered an earlier no-op

configuration.

basicConfig() is a no-op if the root logger already has handlers, so configuration performed after any prior logging call (or in a different import order) is silently ignored, leaving records unhandled. Propagation is on by default (B false), levels default to WARNING but that filters only lower-severity records, not all (C overgeneralized), and dotted names are not required for hierarchy (D false).

32. Under python -O, a module relies on assert to validate an untrusted

deserialization payload before pickle.loads. Which statement most accurately

characterizes the security consequence?

A. -O strips asserts, so the validation vanishes and arbitrary code execution via pickle may proceed unchecked. B. -O converts asserts to warnings, so validation still runs but failures are downgraded to non-fatal log entries. C. -O only disables asserts inside __debug__ blocks, so module-level asserts remain active and safe. D. -O disables asserts but pickle.loads independently re-validates the payload via its own opcode whitelist.

Answer: A. -O strips asserts, so the validation vanishes and arbitrary code

execution via pickle may proceed unchecked.

-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. 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.

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. Branch coverage via coverage.py --branch; it flags the unexecuted

handler path as a partial branch.

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).

37. A team configures logging.config.dictConfig with a QueueHandler feeding a

QueueListener. Under high load, log records are dropped. Which configuration

change most directly addresses this?

A. Increase the root logger level to DEBUG to ensure records are enqueued. B. Set queue to a bounded queue.Queue(maxsize=N) and handle queue.Full by blocking or applying backpressure. C. Add a second StreamHandler to the root logger to duplicate records to stderr. D. Disable propagate on all child loggers to reduce record volume.

Answer: B. Set queue to a bounded queue.Queue(maxsize=N) and handle

queue.Full by blocking or applying backpressure.

Dropped records under load typically stem from a bounded queue that discards on Full; explicit backpressure or blocking enqueue preserves records. Level changes (A) do not affect capacity, extra handlers (C) bypass the queue, and disabling propagation (D) loses records rather than preserving them.

38. A property-based test uses Hypothesis to validate a parse_amount function. A

counterexample shrinks to b"\x00". Which interpretation best reflects Hypothesis's

shrinking behavior?

A. The shrunk input is the original failing case; shrinking only minimizes string length, not structure. B. Shrinking searches for a simpler input that still fails, so b"\x00" is a minimal reproducible counterexample for the property. C. The shrunk input indicates the property is vacuously true for all other inputs. D. Shrinking randomizes the seed to find a different failure, so the counterexample is not reproducible.

Answer: B. Shrinking searches for a simpler input that still fails, so b"\x00" is a

minimal reproducible counterexample for the property.

Hypothesis shrinking reduces a failing example to a minimal input that still violates the property, yielding a small reproducible counterexample like b"\x00". It is not merely length reduction (A), does not imply vacuous truth (C), and shrinking is deterministic given the failure (D).

39. A codebase uses assert for input validation in a public API. A reviewer

recommends replacing them with explicit if ... raise ValueError. Which principle

best justifies this change?

A. Asserts are slower than explicit raises, so performance is the primary concern. B. Asserts express internal invariants and are removed under -O, so they must not enforce public contract validation. C. Explicit raises integrate with logging, whereas asserts cannot be logged. D. Asserts cannot include error messages, so they provide no diagnostic value.

Answer: B. Asserts express internal invariants and are removed under -O, so

they must not enforce public contract validation.

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. Parameterize over encoded variants (..%2f, ..\, null-byte suffixes)

and assert each raises or normalizes to a safe path.

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.