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
50 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Configure Python logging to prevent sensitive data leakage and injection attacks while preserving
auditability
2 Analyze the behavior of assert statements under -O optimization and select appropriate runtime validation
strategies
3 Interpret and integrate outputs from static code analysis tools (Bandit, Semgrep, mypy) into a secure
SDLC
4 Design property-based and mutation-tested suites that expose real faults rather than tautological or brittle
tests
5 Apply taint analysis and input validation principles to remediate injection and deserialization vulnerabilities
in Python
6 WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging
7 Assertions
8 Static Code Analysis & Testing 2026
9 Foundations of Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing
10 Applied Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing
11 Advanced Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing
12 Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing Review
ABSTRACT
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 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

50 QUESTIONS

TABLE OF CONTENTS

# TOPIC 1 Configure Python logging to prevent sensitive data leakage and injection attacks while preserving auditability 2 Analyze the behavior of assert statements under -O optimization and select appropriate runtime validation strategies 3 Interpret and integrate outputs from static code analysis tools (Bandit, Semgrep, mypy) into a secure SDLC 4 Design property-based and mutation-tested suites that expose real faults rather than tautological or brittle tests 5 Apply taint analysis and input validation principles to remediate injection and deserialization vulnerabilities in Python 6 WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging 7 Assertions 8 Static Code Analysis & Testing 2026 9 Foundations of Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 10 Applied Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 11 Advanced Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing 12 Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing Review

ABSTRACT

This study document brings together 50 carefully worded exam questions drawn from WGU D Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026, with the strongest emphasis placed on 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 and mypy) into a secure SDLC. 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 CONFIGURE PYTHON LOGGING TO PREVENT SENSITIVE DATA LEAKAGE AND

INJECTION ATTACKS WHILE PRESERVING AUDITABILITY

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. CORRECT C. Wrap the log call in a try/except to catch injection exceptions. D. Encode the username with base64 before logging. 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.

Q4 CONFIGURE PYTHON LOGGING TO PREVENT SENSITIVE DATA LEAKAGE AND

INJECTION ATTACKS WHILE PRESERVING AUDITABILITY

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. CORRECT C. Running the suite under pytest -x to stop on first failure. D. Adding more assertions inside the function under test. 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.

Q5 CONFIGURE PYTHON LOGGING TO PREVENT SENSITIVE DATA LEAKAGE AND

INJECTION ATTACKS WHILE PRESERVING AUDITABILITY

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. CORRECT C. Convert all queries to string concatenation to satisfy the rule. D. Add # nosemgrep to every flagged line. RATIONALE: 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.

Q6 ANALYZE THE BEHAVIOR OF ASSERT STATEMENTS UNDER -O OPTIMIZATION AND

SELECT APPROPRIATE RUNTIME VALIDATION STRATEGIES

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. CORRECT C. mypy will raise a runtime error when Any is used. D. Disabling that flag only affects documentation generation. RATIONALE: 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.

Q7 ANALYZE THE BEHAVIOR OF ASSERT STATEMENTS UNDER -O OPTIMIZATION AND

SELECT APPROPRIATE RUNTIME VALIDATION STRATEGIES

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. CORRECT C. Mutation testing requires 100% branch coverage to run. D. The stub returns success, which is the expected behavior. 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.

Q10 ANALYZE THE BEHAVIOR OF ASSERT STATEMENTS UNDER -O OPTIMIZATION AND

SELECT APPROPRIATE RUNTIME VALIDATION STRATEGIES

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. CORRECT D. Run bandit with -s B101 to skip assert checks. 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.

Q11 INTERPRET AND INTEGRATE OUTPUTS FROM STATIC CODE ANALYSIS TOOLS

(BANDIT, SEMGREP, MYPY) INTO A SECURE SDLC

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 CORRECT C. Availability, because -O disables exception handling D. Non-repudiation, because assert writes no audit record 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.

Q12 INTERPRET AND INTEGRATE OUTPUTS FROM STATIC CODE ANALYSIS TOOLS

(BANDIT, SEMGREP, MYPY) INTO A SECURE SDLC

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

Q13 INTERPRET AND INTEGRATE OUTPUTS FROM STATIC CODE ANALYSIS TOOLS

(BANDIT, SEMGREP, MYPY) INTO A SECURE SDLC

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 CORRECT D. Escape single quotes in uid with a regex RATIONALE: 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.

Q16 DESIGN PROPERTY-BASED AND MUTATION-TESTED SUITES THAT EXPOSE REAL

FAULTS RATHER THAN TAUTOLOGICAL OR BRITTLE TESTS

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 CORRECT C. Add # noqa: C901 to every migration file D. Use mypy --strict with per-module overrides 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.

Q17 DESIGN PROPERTY-BASED AND MUTATION-TESTED SUITES THAT EXPOSE REAL

FAULTS RATHER THAN TAUTOLOGICAL OR BRITTLE TESTS

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 CORRECT D. Catch RecursionError and return None 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.

Q18 DESIGN PROPERTY-BASED AND MUTATION-TESTED SUITES THAT EXPOSE REAL

FAULTS RATHER THAN TAUTOLOGICAL OR BRITTLE TESTS

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 CORRECT C. Delete the type-checking imports D. Run tests with -O to skip the block 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.

Q19 APPLY TAINT ANALYSIS AND INPUT VALIDATION PRINCIPLES TO REMEDIATE

INJECTION AND DESERIALIZATION VULNERABILITIES IN PYTHON

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

Q22 APPLY TAINT ANALYSIS AND INPUT VALIDATION PRINCIPLES TO REMEDIATE

INJECTION AND DESERIALIZATION VULNERABILITIES IN PYTHON

Static analysis flags subprocess.Popen(user_input, shell=True) as CWE-78.

Which remediation most directly eliminates the injection class while preserving

argument semantics for paths containing spaces?

A. Escape spaces and semicolons in user_input before passing to Popen. B. Replace shell=True with shell=False and pass an argument list. CORRECT C. Wrap the call in shlex.quote(user_input) and keep shell=True. D. Switch to os.system with a validated allow-list of characters. RATIONALE: Removing the shell interpreter and passing an argument list eliminates metacharacter interpretation entirely, which is the canonical CWE-78 fix. Escaping (A, C) is error-prone and still shell-dependent; os.system (D) is strictly worse.

Q23 WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE SOFTWARE SECURITY &

TESTING PYTHON LOGGING

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. CORRECT C. Replace with self.assertEqual from unittest for richer diffs. D. Add --tb=no to suppress the traceback and rely on logs. RATIONALE: 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.

Q24 WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE SOFTWARE SECURITY &

TESTING PYTHON LOGGING

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. CORRECT D. Set logging.disable(logging.CRITICAL) in the module. 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.

Q25 WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE SOFTWARE SECURITY &

TESTING PYTHON LOGGING

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. CORRECT C. Patch datetime.datetime with unittest.mock.patch in each test. D. Set the system clock in CI to a fixed date. 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.

Q28 ASSERTIONS

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. CORRECT C. The first element is the minimum of the input. D. The output contains no duplicate values. 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.

Q29 ASSERTIONS

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. CORRECT C. Assertions cannot reference object attributes. D. Assertions raise SystemExit instead of AssertionError. 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.

Q30 ASSERTIONS

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. CORRECT C. Set autospec=True on every patch call. D. Add retries to the test to mask flakiness. RATIONALE: Module-level patches leak across tests and interact poorly with parallel execution; scoping patches to each test isolates state. Autospec improves fidelity but does not address leakage, and retries hide the underlying race.

Q31 STATIC CODE ANALYSIS & TESTING 2026

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. CORRECT 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. RATIONALE: 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).

Q34 STATIC CODE ANALYSIS & TESTING 2026

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

Q35 FOUNDATIONS OF SOFTWARE SECURITY & TESTING - PYTHON LOGGING,

ASSERTIONS, STATIC CODE ANALYSIS & TESTING

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

Q36 FOUNDATIONS OF SOFTWARE SECURITY & TESTING - PYTHON LOGGING,

ASSERTIONS, STATIC CODE ANALYSIS & TESTING

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. CORRECT D. Replace yield with return and rely on addfinalizer to run rollback after the test. 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).

Q37 FOUNDATIONS OF SOFTWARE SECURITY & TESTING - PYTHON LOGGING,

ASSERTIONS, STATIC CODE ANALYSIS & TESTING

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. CORRECT 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. RATIONALE: 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.