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-based software security and
testing practices, including structured logging, assertion design, static analysis tooling,
and test architecture. It emphasizes secure coding patterns, tool configuration, and
reasoning about subtle failure modes in production systems.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

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-based software security and

testing practices, including structured logging, assertion design, static analysis tooling,

and test architecture. It emphasizes secure coding patterns, tool configuration, and

reasoning about subtle failure modes in production systems.

1. A security audit reveals that an application logs full HTTP request bodies at

DEBUG level in production, and the log files are world-readable on the host. Which

combination of changes most effectively mitigates the risk while preserving

operational debuggability?

A. Raise the logging level to WARNING and remove all request-body logging B. Introduce a logging filter that redacts sensitive fields, set file permissions to 640, and gate DEBUG logging behind an environment flag C. Switch to syslog and rely on the OS to protect log integrity D. Encrypt the log files at rest and continue logging all request bodies at DEBUG

Answer: B. Introduce a logging filter that redacts sensitive fields, set file

permissions to 640, and gate DEBUG logging behind an environment flag

Redaction filters remove sensitive data at the source, restrictive permissions limit exposure, and environment-gated DEBUG prevents production leakage. Raising to WARNING (A) destroys debuggability, syslog (C) does not redact content, and encryption at rest (D) still leaves plaintext accessible to the application and any process reading logs.

2. Which statement most accurately distinguishes the appropriate use of assert

statements in production Python code versus their use in test suites?

A. assert is optimized away under python -O, so it should never be used for input validation in production, but is appropriate in tests B. assert should be used for all runtime validation because it raises AssertionError with a clear message C. assert is only valid inside unittest.TestCase methods and is a syntax error elsewhere D. assert statements are always executed regardless of interpreter flags and are therefore safe for security checks

Answer: A. assert is optimized away under python -O, so it should never be used

for input validation in production, but is appropriate in tests

Python's -O flag strips assert statements, making them unreliable for production validation; they are intended for internal sanity checks and test assertions. Option B ignores the -O stripping, C is factually wrong (assert works anywhere), and D is false because -O disables them.

5. mypy reports 'error: Incompatible return value type (got "Optional[str]",

expected "str")' in a function that returns a value from a dict.get() call. Which

change most precisely resolves the type error without weakening type safety?

A. Change the return type annotation to Optional[str] B. Add # type: ignore to the line C. Use a default value in dict.get() or explicitly handle the None case before returning D. Cast the result with typing.cast(str, ...)

Answer: C. Use a default value in dict.get() or explicitly handle the None case

before returning

Handling the None case or providing a default ensures a str is always returned, preserving the contract. Changing the annotation (A) weakens the interface, # type: ignore (B) suppresses rather than fixes, and cast (D) lies to the type checker without runtime guarantee.

6. In a CI pipeline, coverage reports show 95% line coverage but mutation testing

(mutmut) reveals a mutation score of 40%. What does this discrepancy most

strongly indicate about the test suite?

A. The tests execute most lines but fail to assert on the behavior those lines produce B. The coverage tool is misconfigured and should be replaced C. Mutation testing is unreliable and should be ignored D. The codebase has too many lines to test effectively

Answer: A. The tests execute most lines but fail to assert on the behavior those

lines produce

High line coverage with low mutation score indicates tests run code without meaningful assertions, allowing mutants to survive. B and C misattribute the problem to tooling, and D is irrelevant to the assertion gap.

7. A logging configuration uses a RotatingFileHandler with maxBytes=10MB and

backupCount=5, but an incident shows logs older than the rotation window were lost

during a high-volume attack. Which adjustment most directly improves forensic

retention without unbounded disk growth?

A. Increase the logging level to CRITICAL B. Switch to a TimedRotatingFileHandler with a longer retention interval and off-host shipping C. Disable rotation and write to a single file D. Compress logs in memory before writing

Answer: B. Switch to a TimedRotatingFileHandler with a longer retention interval

and off-host shipping

Timed rotation with longer retention plus off-host shipping preserves forensic data while bounding local disk use. Raising level (A) reduces detail, disabling rotation (C) risks disk exhaustion, and in-memory compression (D) does not address retention.

8. Which pytest feature best supports property-based testing to uncover edge cases a

hand-written example-based test would miss?

A. pytest.mark.parametrize with a fixed list of inputs B. hypothesis.given with strategies generating varied inputs C. pytest.fixture(scope='session') D. pytest.raises context manager

Answer: B. hypothesis.given with strategies generating varied inputs

Hypothesis generates diverse inputs and shrinks failing cases, exposing edge cases beyond fixed examples. Parametrize (A) uses predefined inputs, fixtures (C) manage setup, and pytest.raises (D) only asserts exceptions.

11. A security review flags a module for using assert to validate that an

authenticated user's role is 'admin' before executing a privileged operation. Why is

this pattern considered a critical vulnerability in production?

A. Assertions raise AssertionError, which is not a subclass of Exception and therefore cannot be caught by standard error handlers. B. Python's -O flag strips assert statements entirely, so the authorization check silently vanishes while the privileged operation still executes. C. Assertions evaluate both operands eagerly, leaking the admin role value into logs through side-channel timing. D. Assertions are only evaluated inside unittest test cases, so production code never runs them.

Answer: B. Python's -O flag strips assert statements entirely, so the authorization

check silently vanishes while the privileged operation still executes.

Running with -O or PYTHONOPTIMIZE removes all assert statements, so an authorization guard built on assert is compiled away and the privileged path runs unchecked. Assertions are for internal invariants, not security enforcement; A is wrong because AssertionError subclasses Exception, C misstates evaluation semantics, and D is false.

12. A team configures a root logger with a StreamHandler at DEBUG and a

FileHandler at ERROR, then calls logging.getLogger('app').warning('x'). Given

Python's effective-level and handler-level filtering rules, what is emitted?

A. Nothing, because the child logger inherits the root's DEBUG level but its own default level is WARNING and propagation is disabled. B. The record is filtered at the logger level (WARNING >= effective level) and then each handler independently decides: stream emits it, file drops it. C. Only the FileHandler emits it, since handler levels override the logger's effective level. D. Both handlers emit it because the root logger's DEBUG level is the lowest configured threshold.

Answer: B. The record is filtered at the logger level (WARNING >= effective level)

and then each handler independently decides: stream emits it, file drops it.

A record passes the logger's effective level first, then each attached handler applies its own level: the DEBUG stream handler emits the WARNING, while the ERROR file handler discards it. A is wrong because child loggers default to NOTSET and inherit the root level; C and D invert the two-stage filtering model.

13. An audit requires every log record to be traceable to the originating request in a

multithreaded service. Which logging configuration correctly attaches a per-request

correlation ID without cross-thread leakage?

A. Set a module-level global CORRELATION_ID and reference it in the formatter string. B. Use a logging.Filter that reads contextvars.ContextVar and injects the ID into record.dict before formatting. C. Subclass logging.Formatter and read threading.current_thread().ident as the correlation ID. D. Call logging.basicConfig(extra={'correlation_id': id}) once at application startup.

Answer: B. Use a logging.Filter that reads contextvars.ContextVar and injects the

ID into record.dict before formatting.

A Filter that pulls from a ContextVar (or threading.local for threads) injects the per-request ID into each record safely at emit time. Global state (A) and thread IDs (C) leak or misidentify requests, and basicConfig's extra (D) applies only to that single call, not subsequent records.

14. A CI pipeline runs mypy --strict and pylint over a codebase. A developer

argues that passing mypy --strict makes pylint redundant for catching defects.

Which statement best characterizes the complementary roles of these static analysis

tools?

A. mypy subsumes pylint because type checking is strictly stronger than linting. B. mypy verifies type consistency across annotations; pylint detects style, unused code, and semantic smells (e.g., dangerous default arguments) that type systems cannot express. C. pylint performs dataflow analysis, so it detects all type errors that mypy reports. D. Both tools use the same AST and produce identical diagnostics; running both is purely redundant.

Answer: B. mypy verifies type consistency across annotations; pylint detects style,

unused code, and semantic smells (e.g., dangerous default arguments) that type

systems cannot express.

Static type checkers validate annotation consistency but cannot flag mutable default arguments, unused imports, or style violations that pylint targets via its own checkers. A and D wrongly claim redundancy; C overstates pylint's type-inference capability.

17. A team adopts property-based testing with Hypothesis for a sort function.

Which property set constitutes the strongest specification-based oracle?

A. Assert the output length equals the input length and that the first element is the minimum. B. Assert the output is sorted, is a permutation of the input (same multiset), and is idempotent under re-sorting. C. Assert the output equals a hard-coded expected list for a fixed input. D. Assert the output type is list and that no exception is raised for any input.

Answer: B. Assert the output is sorted, is a permutation of the input (same

multiset), and is idempotent under re-sorting.

Sortedness, permutation equivalence, and idempotence together fully characterize a correct sort, catching both ordering and data-loss bugs. A is incomplete (misses permutation), C is example-based not property-based, and D verifies nothing about correctness.

18. A SAST tool reports a high-severity finding: user input flows into

subprocess.run(cmd, shell=True). Which remediation most directly eliminates the

injection class while preserving functionality?

A. Escape shell metacharacters in the input with a regex before concatenation. B. Pass the command as a list of arguments and set shell=False, avoiding shell interpretation entirely. C. Wrap the call in a try/except to catch injection-induced errors. D. Log the command at ERROR level so injections are auditable.

Answer: B. Pass the command as a list of arguments and set shell=False, avoiding

shell interpretation entirely.

Using an argument list with shell=False removes the shell from the execution path, structurally preventing command injection. Escaping (A) is error-prone and bypassable, C only handles symptoms, and D provides no security control.

19. A CI gate fails when branch coverage drops below 85%, yet a critical

authentication bypass ships undetected. Which testing principle best explains this

failure of the gate?

A. Branch coverage is a weaker metric than statement coverage, so the gate is misconfigured. B. Coverage measures executed code, not the adequacy of assertions or the exploration of input space, so high coverage can coexist with untested security-relevant behavior. C. Coverage tools cannot measure code that uses assertions, so security paths are invisible. D. The gate should use mutation testing exclusively, since coverage is always meaningless.

Answer: B. Coverage measures executed code, not the adequacy of assertions or

the exploration of input space, so high coverage can coexist with untested

security-relevant behavior.

Coverage quantifies which lines/branches executed, not whether assertions validate behavior or whether adversarial inputs were explored; a bypass can sit on a covered branch with no effective oracle. A misstates the metric hierarchy, C is false, and D overstates the case against coverage.

20. A developer wants to guarantee that a production service never emits stack

traces containing secrets, even when unexpected exceptions occur. Which logging

configuration achieves this most robustly?

A. Set the logger level to CRITICAL so lower-severity exceptions are never logged. B. Attach a custom Filter that redacts sensitive patterns from record.msg, record.args, and record.exc_info before formatting, and log exceptions with exc_info=True. C. Use print() instead of logging for exception output to avoid formatter processing. D. Disable propagation and rely on the default formatter, which omits exception details.

Answer: B. Attach a custom Filter that redacts sensitive patterns from record.msg,

record.args, and record.exc_info before formatting, and log exceptions with

exc_info=True.

A redacting Filter that scrubs msg, args, and exc_info is the only approach that sanitizes both the message and the traceback regardless of severity. A suppresses rather than redacts, C bypasses logging controls entirely, and D is false - the default formatter does include exception text.

23. A repository's CI runs bandit -r src/ and reports B608 (hardcoded SQL) on a

line using a parameterized query with a constant table name. What is the most

defensible engineering response?

A. Suppress B608 globally in the Bandit config to keep the build green. B. Refactor the query to remove the constant table name. C. Add a targeted # nosec B608 with a comment justifying the constant, since the table name is not user-controlled. D. Switch from Bandit to Pylint, which does not flag SQL construction.

Answer: C. Add a targeted # nosec B608 with a comment justifying the constant,

since the table name is not user-controlled.

A targeted # nosec B608 with justification is the accepted practice for a verified false positive, preserving the rule's signal elsewhere. Global suppression (A) blinds the tool to real findings, refactoring a constant table name (B) is unnecessary, and switching tools (D) merely hides the issue rather than resolving it.

24. A developer writes assert user.is_admin to gate a privileged operation in

production code. Which statement best characterizes the security risk?

A. Assertions are removed when Python runs with -O, so the check silently disappears, enabling privilege bypass. B. Assertions raise AssertionError, which is uncaught and crashes the process, causing a denial of service. C. Assertions are evaluated lazily, so the check may not run on the first call. D. Assertions cannot reference attributes, so user.is_admin is always falsy.

Answer: A. Assertions are removed when Python runs with -O, so the check

silently disappears, enabling privilege bypass.

The -O flag strips assert statements entirely, so a security gate built on assert vanishes in optimized deployments. Assertions are eager, not lazy (C), can reference attributes (D), and an AssertionError crash (B) is a lesser concern than the silent bypass.

25. A test suite uses unittest.mock.patch on requests.get and asserts it was called

once. The production code actually calls requests.get via an aliased import `from

requests import get`. Why might the test pass while production remains broken?

A. patch replaces the attribute on the module object, so aliased references bound earlier are unaffected, and the assertion checks the wrong target. B. patch only works on class methods, not module-level functions. C. requests.get is a C extension and cannot be patched. D. The mock returns a MagicMock that always equals the real response.

Answer: A. patch replaces the attribute on the module object, so aliased references

bound earlier are unaffected, and the assertion checks the wrong target.

patch('requests.get') rebinds the attribute on the requests module, but from requests import get created an independent name binding in the importing module, so the production call bypasses the mock. The assertion then verifies a call that never occurred in the real path, giving a false green. patch works on module functions (B), requests is pure Python (C), and MagicMock equality (D) is irrelevant.

26. Which property of pytest.mark.parametrize most improves failure diagnosis

compared to a loop over cases inside a single test function?

A. It runs cases in parallel across processes by default. B. It generates a distinct test ID per parameter set, so failures localize to a single case. C. It caches results so re-runs skip unchanged cases. D. It automatically retries flaky parameter sets.

Answer: B. It generates a distinct test ID per parameter set, so failures localize to a

single case.

Parametrize yields one test item per case with a unique ID, so a failure points to the specific inputs rather than aborting the loop at the first failure. Parallelism (A), caching (C), and retries (D) are not default behaviors of parametrize.

29. A flaky test fails only when run in the full suite but passes in isolation. The test

relies on a module-level mutable list that another test mutates. Which fix best

addresses the root cause?

A. Add time.sleep(0.1) before the assertion to stabilize timing. B. Mark the test with @pytest.mark.flaky(reruns=3) to mask the failure. C. Replace the shared module-level list with a fixture that constructs a fresh instance per test. D. Reorder the suite so the offending test runs first.

Answer: C. Replace the shared module-level list with a fixture that constructs a

fresh instance per test.

The failure is test pollution from shared mutable state; a per-test fixture restores isolation and eliminates order dependence. Sleeping (A) does not fix shared state, reruns (B) hide the defect, and reordering (D) leaves the latent coupling in place.

30. In a security review, which use of eval() is least objectionable from a

secure-coding standpoint?

A. eval(user_input) to evaluate a user-supplied arithmetic expression. B. eval(config_string) where config_string is loaded from an untrusted network source. C. ast.literal_eval(user_input) restricted to literals, used instead of eval for parsing. D. eval(open('plugin.py').read()) to dynamically load plugins at runtime.

Answer: C. ast.literal_eval(user_input) restricted to literals, used instead of eval

for parsing.

ast.literal_eval parses only Python literals and raises on arbitrary expressions, eliminating code execution-the safe replacement for eval in parsing scenarios. Options A, B, and D all evaluate untrusted or attacker-influenced input with full interpreter semantics, enabling arbitrary code execution.

31. A test suite uses caplog.at_level(logging.WARNING) while the module under

test configures logging.basicConfig(level=logging.INFO) at import time. Which

statement best explains why the test still captures INFO-level records emitted inside

the function?

A. caplog.at_level temporarily lowers the handler level, but the root logger level set by basicConfig still filters INFO records before propagation. B. caplog.at_level sets both the logger and handler levels to WARNING, so INFO records are dropped unless propagate is disabled. C. caplog.at_level sets the level on the handler attached by caplog and on the specified logger, but records are still gated by the effective level of the originating logger, which basicConfig may have left at INFO. D. basicConfig is idempotent and therefore ignored during tests, so the root logger defaults to WARNING and caplog's handler level is the only filter.

Answer: C. caplog.at_level sets the level on the handler attached by caplog and on

the specified logger, but records are still gated by the effective level of the

originating logger, which basicConfig may have left at INFO.

caplog.at_level sets the level on the caplog handler and on the named logger, but emission is still gated by the originating logger's effective level; basicConfig's INFO setting on the root logger can therefore allow INFO records through. Options A and B misdescribe which levels caplog manipulates, and D incorrectly claims basicConfig is a no-op when it is actually idempotent only after the first successful call.

32. Which assertion style is LEAST appropriate for a production module that must

run under python -O, and why?

A. Using if not condition: raise ValueError(...) because it adds branching overhead that the optimizer cannot remove. B. Using assert isinstance(x, int) for input validation because -O strips assert statements entirely, removing the check. C. Using unittest.TestCase.assertTrue because unittest assertions are also removed under -O. D. Using typing.cast for narrowing because casts are erased at runtime regardless of optimization flags.

Answer: B. Using assert isinstance(x, int) for input validation because -O strips

assert statements entirely, removing the check.

The -O flag removes assert statements, so any validation relying on assert silently disappears in optimized builds. unittest assertions and raise-based checks are not stripped by -O, and typing.cast is a no-op at runtime by design, making it unsuitable for runtime validation but not because of -O.

35. A logging.handlers.RotatingFileHandler is configured with maxBytes=1024

and backupCount=3. After the handler has rotated four times, how many total log

files exist on disk, and which file contains the oldest retained records?

A. Four files; the oldest records are in the file with no numeric suffix. B. Three files; the oldest records are in app.log.3. C. Four files; the oldest records are in app.log.3. D. Three files; the oldest records are in the file with no numeric suffix.

Answer: C. Four files; the oldest records are in app.log.3.

RotatingFileHandler keeps the active file plus backupCount rotated files, so with backupCount=3 there are four files total. The highest-numbered backup (app.log.3) holds the oldest retained records, while the unsuffixed file holds the most recent.

36. Which statement best characterizes the difference between unittest.mock.patch

and patch.object when the target is imported as from module import func inside

the code under test?

A. Both patch the same object because Python resolves func through module at call time. B. patch patches the attribute on the module where it is defined; patch.object patches it on the importing module, so only patch.object works for the rebinding case. C. Neither works; from-imports create immutable bindings that cannot be patched. D. patch targets the name in the module where it is looked up (the importing module), so patch('importer.func') is required; patch.object on the defining module has no effect on the importer's binding.

Answer: D. patch targets the name in the module where it is looked up (the

importing module), so patch('importer.func') is required; patch.object on the

defining module has no effect on the importer's binding.

After from module import func, the importing module holds its own reference, so the patch must target that binding (importer.func); patching the defining module leaves the importer's reference untouched. Options A and B invert the lookup semantics, and C is false because the binding can be replaced.

37. A CI pipeline runs pytest --cov=src --cov-fail-under=90 and passes, yet a critical

branch is untested. Which coverage refinement most directly addresses this gap?

A. Switching to statement coverage and raising the threshold to 100%. B. Enabling branch coverage with --cov-branch so partial branches are counted as uncovered. C. Adding --cov-report=html to visualize the report. D. Using coverage combine to merge parallel runs before enforcing the threshold.

Answer: B. Enabling branch coverage with --cov-branch so partial branches are

counted as uncovered.

Statement coverage can be satisfied while a conditional branch is never taken; --cov-branch measures both branch outcomes and would expose the untested path. HTML reports and combining runs change reporting/aggregation, not the metric, and 100% statement coverage still permits untaken branches.

38. Which practice best mitigates log injection (CWE-117) when user-controlled data

is written to a plain-text log?

A. Encode the log message with base64 before passing it to the logger. B. Use logging.Formatter with %(message)s and rely on the logger's thread safety. C. Strip or escape CR/LF characters and prefer structured logging (e.g., JSON) that separates data from the message field. D. Set the logger level to WARNING so untrusted INFO records are discarded.

Answer: C. Strip or escape CR/LF characters and prefer structured logging (e.g.,

JSON) that separates data from the message field.

Log injection exploits unescaped newlines and control characters to forge log entries; sanitizing CR/LF and using structured formats that treat user data as a value rather than part of the message prevents it. Base64 obfuscates rather than neutralizes, formatters do not sanitize, and raising the level does not remove injection risk.