Docsity

WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API,, Exams of Computer Security

Toggle sidebar
bg1
WGU D385 Pytest & Security Unit Testing
Workbook 48 Practice Tests, Python Security, API,
Exams of Computer Security - Complete 50
Verified Q&A with Answers & Rationales for Exam
Prep
Q1
In Pytest, which fixture scope best isolates a mocked API auth token per test while allowing module-level
setup?
A. function scope with yield teardown
B. session scope with autouse
C. module scope with monkeypatch
D. class scope with fixture finalizer
Answer: A
Rationale: Function-scoped fixtures with yield ensure each test gets a fresh token and teardown,
preventing state leakage. Session or module scopes risk cross-test contamination; class scope is too
broad for per-test isolation.
Q2
An API returns 200 for a request with another user's ID in the URL. Which OWASP API risk is
demonstrated?
A. Broken Object Level Authorization (BOLA)
B. Mass Assignment
C. Security Misconfiguration
D. Insufficient Logging
Answer: A
Rationale: BOLA (API1:2023) occurs when an endpoint fails to verify that the requested object belongs to
the authenticated user, allowing horizontal privilege escalation. Mass assignment involves binding client
input to internal fields; misconfiguration and logging are separate risks.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download WGU D385 Pytest & Security Unit Testing Workbook 48 Practice Tests, Python Security, API, and more Exams Computer Security in PDF only on Docsity!

WGU D385 Pytest & Security Unit Testing

Workbook 48 Practice Tests, Python Security, API,

Exams of Computer Security - Complete 50

Verified Q&A with Answers & Rationales for Exam

Prep

Q

In Pytest, which fixture scope best isolates a mocked API auth token per test while allowing module-level setup?

A. function scope with yield teardown B. session scope with autouse C. module scope with monkeypatch D. class scope with fixture finalizer

Answer: A Rationale: Function-scoped fixtures with yield ensure each test gets a fresh token and teardown, preventing state leakage. Session or module scopes risk cross-test contamination; class scope is too broad for per-test isolation.

Q

An API returns 200 for a request with another user's ID in the URL. Which OWASP API risk is demonstrated?

A. Broken Object Level Authorization (BOLA) B. Mass Assignment C. Security Misconfiguration D. Insufficient Logging

Answer: A Rationale: BOLA (API1:2023) occurs when an endpoint fails to verify that the requested object belongs to the authenticated user, allowing horizontal privilege escalation. Mass assignment involves binding client input to internal fields; misconfiguration and logging are separate risks.

Which Pytest feature most effectively tests multiple malicious payloads against an input validator without duplicating code?

A. pytest.mark.parametrize B. pytest.fixture(autouse=True) C. pytest.mark.skipif D. pytest.raises

Answer: A Rationale: Parametrization runs the same test logic over a list of payloads, enabling comprehensive coverage of injection vectors with minimal code. Fixtures handle setup, skipif conditionally skips, and raises asserts exceptions-none scale payload testing as cleanly.

Q

A CI pipeline runs Bandit and reports B608 (SQL injection). Which remediation best aligns with NIST SSDF PW.5?

A. Replace string-concatenated SQL with parameterized queries B. Suppress the finding in the Bandit config C. Add a WAF rule to block SQLi patterns D. Increase logging of SQL errors

Answer: A Rationale: NIST SSDF PW.5 requires eliminating vulnerabilities at the source; parameterized queries prevent SQL injection by separating code from data. Suppression hides the issue, WAF is defense-in-depth not a fix, and logging does not remediate.

Q

Which test best verifies that a JWT is rejected after its 'exp' claim has passed?

A. Freeze time beyond expiry, call endpoint, assert 401 B. Mock jwt.decode to return expired payload C. Assert token string contains 'exp' field D. Decode token and compare exp to current time

Answer: A Rationale: Only an integration-style test that advances time past expiry and asserts the endpoint rejects the token validates the full validation path. Mocking decode bypasses real logic; string checks and manual comparison do not test enforcement.

Which Pytest plugin best supports security regression testing by recording and replaying HTTP interactions?

A. pytest-recording (VCR.py) B. pytest-cov C. pytest-xdist D. pytest-benchmark

Answer: A Rationale: pytest-recording integrates VCR.py to record/replay HTTP, enabling deterministic security regression tests against APIs. pytest-cov measures coverage, xdist parallelizes, and benchmark measures performance.

Q

A test asserts that a 403 is returned for a low-privilege user accessing an admin route. Which property is being validated?

A. Vertical privilege escalation prevention B. Horizontal privilege escalation prevention C. Session fixation resistance D. CSRF token validation

Answer: A Rationale: Vertical privilege escalation involves a lower-privileged user attempting to access higher-privileged functionality; a 403 confirms enforcement. Horizontal escalation is same-level cross-user access; session fixation and CSRF are different mechanisms.

Q

In Pytest, which fixture scope most effectively isolates a database transaction rollback per test?

A. session B. module C. function D. class

Answer: C Rationale: Function-scoped fixtures are instantiated per test, ensuring each test gets a fresh transaction that can be rolled back independently. Session, module, and class scopes persist across multiple tests, risking state leakage and order-dependent failures.

Which OWASP API Security Top 10 (2023) risk is mitigated by enforcing object-level authorization checks?

A. API1: Broken Object Level Authorization B. API2: Broken Authentication C. API3: Broken Object Property Level Authorization D. API4: Unrestricted Resource Consumption

Answer: A Rationale: API1:2023 specifically addresses Broken Object Level Authorization (BOLA), where an attacker manipulates object IDs to access unauthorized resources. Object-level authorization checks ensure the authenticated user has permission to access the requested object. API2 concerns authentication mechanisms, API3 concerns property-level exposure, and API4 concerns rate limiting.

Q

Which Python construct most reliably prevents SQL injection when parameterizing queries with sqlite3?

A. String concatenation with user input B. f-strings with escaped quotes C. Parameterized queries using? placeholders D. Input sanitization via regex

Answer: C Rationale: Parameterized queries with placeholders (e.g.,? in sqlite3) separate SQL code from data, preventing injection by design. String concatenation and f-strings embed user input directly into SQL, and regex sanitization is error-prone and bypassable.

Q

In Pytest, which hook customizes test collection to include only functions with a specific marker?

A. pytest_collection_modifyitems B. pytest_configure C. pytest_generate_tests D. pytest_addoption

Answer: A Rationale: pytest_collection_modifyitems allows modification of the collected test items, such as filtering based on markers. pytest_configure registers markers, pytest_generate_tests handles parametrization, and pytest_addoption adds command-line options.

Which Pytest plugin is specifically designed for measuring code coverage during security unit tests?

A. pytest-cov B. pytest-html C. pytest-xdist D. pytest-mock

Answer: A Rationale: pytest-cov integrates coverage.py with Pytest to report code coverage, helping identify untested security-critical paths. pytest-html generates reports, pytest-xdist enables parallel testing, and pytest-mock provides mocking utilities.

Q

In secure unit testing, which practice ensures test data does not leak sensitive information?

A. Using production data for realism B. Hardcoding credentials in test files C. Employing synthetic data and environment variables D. Logging all test inputs and outputs

Answer: C Rationale: Synthetic data avoids exposing real sensitive information, and environment variables keep secrets out of source code. Using production data risks leaks, hardcoding credentials is insecure, and logging inputs/outputs can inadvertently expose sensitive data.

Q

Which CI integration step is critical for enforcing security unit tests before deployment?

A. Running tests only on the main branch B. Failing the build on any test failure C. Skipping tests for hotfixes D. Using a single environment for all tests

Answer: B Rationale: Failing the build on test failures ensures that security tests act as a gate, preventing vulnerable code from being deployed. Running tests only on main, skipping for hotfixes, or using a single environment undermines the effectiveness of security testing.

Which pytest feature best isolates a flaky API test's network dependency without altering production code?

A. monkeypatch.setenv to override the API base URL to a local stub server B. pytest.mark.skipif with a condition on network availability C. responses or requests-mock fixture to intercept and stub HTTP calls D. pytest-xdist with --dist=loadfile to parallelize and retry failures

Answer: C Rationale: responses/requests-mock intercept HTTP at the adapter level, providing deterministic stubs without code changes; skipif merely skips, monkeypatch.setenv requires a running stub, and xdist does not isolate network calls.

Q

An API returns 200 with a JSON body for a request lacking Authorization. Which OWASP API Security Top 10 2023 category is violated?

A. API1:2023 Broken Object Level Authorization B. API2:2023 Broken Authentication C. API5:2023 Broken Function Level Authorization D. API8:2023 Security Misconfiguration

Answer: B Rationale: Returning protected data without any authentication check is Broken Authentication (API2); BOLA concerns object-level access after auth, BFLA concerns role/function checks, and misconfiguration is broader configuration weakness.

Q

Which pytest fixture scope minimizes cost while preserving isolation for a database connection used read-only across a module?

A. function B. class C. module D. session

Answer: C Rationale: Module scope reuses the read-only connection across tests in a module, balancing cost and isolation; function scope is costly, class scope is narrower, and session scope risks cross-module state leakage.

Which assertion pattern best detects a timing side channel in a token comparison function during unit testing?

A. assert result == expected using pytest.approx B. Statistical comparison of many timed calls with hmac.compare_digest baseline C. Mocking time.time to return fixed values D. Using pytest-benchmark to assert mean latency below threshold

Answer: B Rationale: Timing side channels require statistical analysis across many samples compared to a constant-time baseline; single assertions, mocked clocks, and mean-latency thresholds cannot reliably detect early-exit behavior.

Q

Which NIST SSDF SP 800-218 practice most directly maps to maintaining a pytest security regression suite?

A. PO.1: Define security requirements for software B. PW.7: Review and/or analyze human-readable code C. PW.8: Test executable code to identify vulnerabilities D. PS.2: Provide a mechanism to verify software integrity

Answer: C Rationale: PW.8 addresses testing executable code for vulnerabilities, aligning with an automated security regression suite; PO.1 is requirements, PW.7 is code review, and PS.2 is release integrity.

Q

Which pytest construct best verifies that a function raises ValueError with a specific message under invalid input?

A. with pytest.raises(ValueError): func('bad') B. with pytest.raises(ValueError, match='invalid input'): func('bad') C. assert func('bad') is None D. pytest.warns(ValueError, match='invalid input')

Answer: B Rationale: pytest.raises with match asserts both exception type and message via regex; plain raises ignores the message, the None assertion is unrelated, and pytest.warns targets warnings not exceptions.

Which CI configuration best prevents a pytest security suite from silently passing when tests are deselected?

A. pytest -m security --continue-on-collection-errors B. pytest -m security --strict-markers --maxfail= C. pytest -m security -p no:cacheprovider D. pytest -m security --exitfirst --deselect=none

Answer: B Rationale: --strict-markers fails on unknown markers, preventing silent deselection from typos, while --maxfail ensures early failure; other flags do not guard against marker misconfiguration.

Q

Which pytest fixture scope best isolates a mutable global used by API auth tests across parallel xdist workers?

A. session scope with autouse=True B. module scope with a factory fixture C. function scope with monkeypatch D. package scope with a finalizer

Answer: C Rationale: Function-scoped monkeypatch reverts mutations after each test, preventing cross-test and cross-worker leakage; session scope persists across tests, module/package scopes still share state within a worker, and autouse does not isolate.

Q

An API returns 200 with a JWT whose 'alg' is 'none'. Which test assertion best detects this vulnerability?

A. Assert response.status_code == 401 for unsigned tokens B. Decode header and assert alg not in {'none','HS256'} C. Assert token length exceeds 100 characters D. Assert signature verifies with the server public key

Answer: B Rationale: The 'alg:none' bypass is detected by explicitly decoding the JOSE header and rejecting 'none' (and weak algorithms); status-only or length checks miss it, and public-key verification does not apply to unsigned tokens.

In pytest, which mechanism best replaces a database dependency for a security test asserting authorization queries?

A. pytest.mark.skipif on database availability B. tmp_path fixture for SQLite files C. monkeypatch.setenv to point to a test DB D. unittest.mock.patch on the repository method returning canned rows

Answer: D Rationale: Patching the repository boundary isolates the authorization logic and lets tests assert exact query parameters and enforce expected row filtering; skipif, tmp_path, and env vars still exercise real DB behavior.

Q

Which pytest assertion most reliably detects a timing-based user-enumeration flaw in a login endpoint?

A. Assert identical status codes for valid and invalid users B. Assert response bodies are byte-identical C. Statistical comparison of response-time distributions with a significance threshold D. Assert rate limiting returns 429 after N attempts

Answer: C Rationale: Timing side channels require statistical comparison of latency distributions (e.g., Mann-Whitney) because status/body checks and rate limits do not reveal constant-time behavior differences.

Q

Which practice best prevents test pollution when security tests mutate environment variables and filesystem state?

A. Rely on session-scoped fixtures to reset once B. Use autouse function-scoped fixtures with monkeypatch and tmp_path C. Run tests serially without parallelism D. Order tests alphabetically to avoid conflicts

Answer: B Rationale: Autouse function-scoped fixtures using monkeypatch (env) and tmp_path (files) guarantee per-test isolation; session resets leak state, serial execution does not prevent ordering effects, and alphabetical ordering is fragile.

A test asserts a password hash is stored using Argon2id with recommended parameters. Which assertion is most appropriate?

A. Assert hash string starts with '$argon2id$' and verify with argon2-cffi B. Assert hash length equals 60 characters C. Assert hash equals a fixed known value D. Assert hash does not contain the plaintext password

Answer: A Rationale: Checking the PHC prefix and verifying via argon2-cffi confirms algorithm and parameter encoding; length checks fit bcrypt, fixed values break due to random salts, and substring checks are insufficient.

Q

Which pytest plugin configuration best integrates SAST findings as failing tests in CI under NIST SSDF PW.7?

A. pytest-flake8 with max-line-length enforcement B. pytest-benchmark thresholds on request latency C. pytest-bandit or pytest-safety failing on high-severity findings D. pytest-html report generation for manual review

Answer: C Rationale: SSDF PW.7 requires automated code review; wrapping Bandit (SAST) or Safety (dependency CVEs) as pytest tests makes high-severity findings fail the build, whereas linting, benchmarks, and HTML reports do not enforce security gates.

Q

Which pytest feature most directly enables secure parameterization of API authentication tests without leaking secrets into test reports?

A. pytest.mark.parametrize with inline literal credentials B. pytest.fixture with scope='session' and monkeypatch C. pytest.fixture(autouse=True) reading env vars via os.environ D. pytest.mark.parametrize with indirect=True and a fixture sourcing secrets from a vault

Answer: D Rationale: Indirect parameterization routes parameters through a fixture, allowing secrets to be fetched from a secure vault at runtime and never appear in test IDs or reports. Inline literals (A) leak into reports; session-scoped monkeypatch (B) is not designed for secret isolation; autouse env reads (C) still risk exposure and lack per-test control.

Which NIST SSDF SP 800-218 practice group most directly corresponds to integrating automated security unit tests into CI?

A. PO: Prepare the Organization B. PS: Protect the Software C. PW: Produce Well-Secured Software D. RV: Respond to Vulnerabilities

Answer: C Rationale: PW (Produce Well-Secured Software) includes designing, building, and verifying software with security testing such as automated tests in CI. PO covers organizational readiness, PS covers protecting code and environments, and RV covers vulnerability response.

Q

A test uses pytest.raises to verify a password hashing function rejects weak input. Which usage correctly asserts the specific exception and message?

A. with pytest.raises(Exception): hash_password('weak') B. with pytest.raises(ValueError, match='entropy'): hash_password('weak') C. assert pytest.raises(ValueError, hash_password, 'weak') D. with pytest.raises(ValueError) as e: hash_password('weak'); assert 'entropy' in str(e)

Answer: B Rationale: pytest.raises with the exception type and match regex verifies both the class and message pattern concisely. A is too broad; C uses an invalid call form; D works but is less precise and more verbose than match, though both B and D can be defensible-B is the idiomatic, exact form tested.

Q

Which technique best detects a blind SQL injection vulnerability in an API endpoint during automated security testing?

A. Reflected XSS payload injection into JSON fields B. Time-based boolean inference using database sleep functions C. Fuzzing with oversized binary payloads to trigger 500 errors D. Static analysis of ORM query construction only

Answer: B Rationale: Blind SQLi yields no direct output, so time-based inference (e.g., conditional SLEEP) reveals injection through response delays. XSS payloads target scripting, oversized payloads test robustness, and static analysis alone cannot confirm runtime exploitability.

Which pytest plugin configuration most effectively prevents accidental execution of tests that hit live production APIs?

A. Marking live tests with @pytest.mark.live and excluding via addopts = -m 'not live' B. Naming live tests test_live_*.py and relying on default discovery C. Using pytest.skip inside each live test at runtime D. Setting a global timeout via pytest-timeout

Answer: A Rationale: A custom marker plus addopts exclusion prevents collection/execution by default and is explicit and auditable. Naming conventions (B) still collect and run; runtime skip (C) still executes setup and risks partial calls; timeouts (D) do not prevent production access.

Q

In secure unit testing, which practice best validates that error handling does not leak stack traces to API clients?

A. Asserting response body contains no 'Traceback' or file paths on forced exceptions B. Checking that HTTP status is 500 for all exceptions C. Verifying logs contain full stack traces for debugging D. Mocking the logger to suppress error output

Answer: A Rationale: Asserting the client-facing body lacks traceback markers or internal paths directly tests information leakage prevention. Status 500 alone (B) does not prove no leakage; logging traces (C) is server-side and expected; suppressing logs (D) does not test response content.

Q

Which CIS Controls v8.1 safeguard most directly supports maintaining an inventory of authorized software components used in tests?

A. Control 1: Inventory and Control of Enterprise Assets B. Control 2: Inventory and Control of Software Assets C. Control 4: Secure Configuration of Enterprise Assets and Software D. Control 16: Application Software Security

Answer: B Rationale: Control 2 addresses inventory and control of software assets, including authorized libraries and components used in builds and tests. Control 1 covers hardware/assets, Control 4 covers configuration, and Control 16 covers secure development and testing practices.