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 |
WGU D385 Task 1 Performance Assessment Guide |
Comprehensive Examination
WGU D385 Task 1 Performance Assessment Guide Software
Security & Testing Python Logging, Assertions, Static Code
Analysis & Testing 2026 actual exam preparation document
INTRODUCTION
This document is an important and very helpful preparation
resource for WGU D385 Task 1 Performance Assessment Guide
Software Security & Testing Python Logging, Assertions, Static
Code Analysis & Testing 2026. Every item uses a focused exam
stem, four response options, a keyed response, and a clear
rationale, making it easier to understand the subject, spot
distractors, and build real exam confidence.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

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 |

WGU D385 Task 1 Performance Assessment Guide | Comprehensive Examination WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026 actual exam preparation document

INTRODUCTION

This document is an important and very helpful preparation resource for WGU D385 Task 1 Performance Assessment Guide Software Security & Testing Python Logging, Assertions, Static Code Analysis & Testing 2026. Every item uses a focused exam stem, four response options, a keyed response, and a clear rationale, making it easier to understand the subject, spot distractors, and build real exam confidence.

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

Correct Answer: B - Use a JSON formatter that serializes the

message field and escapes control characters.

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.

Question 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

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

Correct Answer: B - Adding property-based tests that assert

invariants across generated inputs, including empty sequences.

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.

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

Correct Answer: B - Verify the ORM's parameterization path

with a taint-mode Semgrep rule and adjust the rule's sanitizer

configuration.

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.

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

Correct Answer: B - Any propagates and suppresses type-based

taint tracking, allowing unsafe flows to pass unchecked.

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.

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

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.

Correct Answer: B - FullLoader is safer than UnsafeLoader but

still permits some complex tags and should be replaced with

safe_load for untrusted data.

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.

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

Correct Answer: C - Override the default exclusion with --include

or remove tests from the excluded set.

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.

Question 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

Correct Answer: B - Integrity of the authorization check, because

assertions are stripped under -O

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.

Question 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

Correct Answer: D - An autouse function-scoped fixture that

restores the dict

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

Correct Answer: B - The logger's effective level filters the record

before it reaches the handler

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

Question 15

A unit test asserts result == 0.1 + 0.2 for a function returning a float. Which

change best reflects sound testing practice for floating-point results?

A. Use pytest.approx(0.3) to compare within a tolerance B. Compare str(result) == '0.3' C. Round both sides to 15 decimals and compare D. Convert both to Decimal and compare exactly

Correct Answer: A - Use pytest.approx(0.3) to compare within a

tolerance

RATIONALE pytest.approx encodes an explicit relative/absolute tolerance, which is the accepted way to test float outputs. String comparison, fixed rounding, and Decimal conversion either hide precision semantics or introduce new representation errors.

Question 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

Correct Answer: B - Configure a linter (e.g., Ruff C901 with

max-complexity) and exclude migrations via extend-exclude

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.

Question 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

Correct Answer: C - Enforce a maximum nesting depth and

reject inputs exceeding it

D. Set the logger level to CRITICAL and remove the log call

Correct Answer: A - Switch to %-style lazy formatting and log a

hashed user identifier

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.

Question 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 ==

Correct Answer: C - Use st.lists(st.integers()) with

@settings(max_examples=1000, deadline=None) and assert

sortedness plus permutation equivalence

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.

Question 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. D. Replace --cov-fail-under with --cov-report=term-missing and parse the output.

Correct Answer: B - Use `--cov=src/new_module

--cov-fail-under=90` alongside the existing global threshold.

RATIONALE pytest-cov supports multiple --cov targets; combining a module-specific --cov with --cov-fail-under=90 enforces the threshold on that module while still measuring the rest. Option A disables enforcement, C changes global source scope, and D removes the hard gate.

Question 22

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

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.

Correct Answer: C - Defer handler configuration to the

application entry point and let pytest manage the root logger.

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.

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

Correct Answer: B - Inject a clock callable (e.g.,

clock=datetime.now) as a default parameter or dependency.

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.

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

Correct Answer: C - Assert on a curated subset of keys plus

type/shape constraints.

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.

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

Correct Answer: B - Replace pickle with a safe format such as

JSON or a schema-validated parser.

Correct Answer: B - Assertions can be stripped when Python runs with -O, silently disabling the check.

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.

Question 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. D. Add retries to the test to mask flakiness.

Correct Answer: B - Use patch as a context manager or

decorator scoped to each test rather than module-level patching.

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.

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

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

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

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