
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































EXAM INFORMATION
Subject: Software Security & Testing - Python Logging, Assertions, Static Code Analysis & Testing Questions: 50 | Format: Multiple choice Duration: 3 hours Passing score: 96%
ABOUT THIS EXAM
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.
WHAT THIS COVERS
Detailed Explanations
Q 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.
EXPLANATION 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.
Detailed Explanations
Q Bandit reports B301 (pickle) on a function that deserializes data from a trusted internal queue, but the queue is fed by a webhook that accepts unauthenticated JSON. Which action best reflects correct triage?
A (^) Suppress B301 with # nosec because the queue is internal.
B (^) Treat the finding as a true positive and replace pickle with a safe format (e.g., JSON) plus schema validation.
CORRECT
C (^) Downgrade severity to LOW because the queue is internal.
D (^) Add a try/except around pickle.loads to catch malicious payloads.
EXPLANATION Taint flows from an unauthenticated webhook through the queue to pickle.loads, making the finding a true positive with potential RCE. Suppression or severity downgrade ignores the taint path, and try/except cannot prevent code execution during deserialization.
Detailed Explanations
Q 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.
EXPLANATION 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.
Detailed Explanations
Q 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.
EXPLANATION 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.
Detailed Explanations
Q 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.
EXPLANATION 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.
Detailed Explanations
Q A function uses yaml.load(data, Loader=yaml.FullLoader) on untrusted input. Static analysis flags it, but the developer argues FullLoader is safe. Which statement is most accurate?
A (^) FullLoader is safe because it disables all Python object construction.
B (^) FullLoader is safer than UnsafeLoader but still permits some complex tags and should be replaced with safe_load for untrusted data.
CORRECT
C (^) FullLoader is identical to UnsafeLoader in all respects.
D (^) yaml.load is safe if the input is UTF-8.
EXPLANATION 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.
Detailed Explanations
Q 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.
EXPLANATION 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.
Detailed Explanations
Q 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
EXPLANATION 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.
Detailed Explanations
Q 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
EXPLANATION 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.
Detailed Explanations
Q 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 CORRECT
B (^) Compare str(result) == '0.3'
C (^) Round both sides to 15 decimals and compare
D (^) Convert both to Decimal and compare exactly
EXPLANATION 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.
Detailed Explanations
Q 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
EXPLANATION 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.
Detailed Explanations
Q 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
EXPLANATION 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.
Detailed Explanations
Q 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
EXPLANATION 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.