Docsity

WGU D385 ZHN1 Task 1 Software Security & Testing | Static Code Analysis, Python Logging, D, Exams of Cybercrime, Cybersecurity and Data Privacy

Partial preview of the text

Download WGU D385 ZHN1 Task 1 Software Security & Testing | Static Code Analysis, Python Logging, D and more Exams Cybercrime, Cybersecurity and Data Privacy in PDF only on Docsity!

WGU D385 ZHN1 Task 1 Software Security &

Testing | Static Code Analysis, Python Logging,

Debugging, Exception Handling & Unit Testing

| 2026/2027 update | with complete solutions..

Section 1: Static Code Analysis (Q1–Q15)

Q1. What is the primary purpose of static code analysis in a Python project? A. To execute the program and observe runtime behavior B. To examine source code for defects, style violations, and security issues without running it C. To measure the execution time of individual functions D. To generate test data automatically Answer: B Rationale: Static analysis examines code at rest—parsing the source or abstract syntax tree—without executing the program. This allows it to catch issues such as undefined names, unused imports, unsafe function calls, and style violations before runtime. Option A describes dynamic analysis or debugging. Option C describes profiling. Option D describes test-generation tooling. Q2. Which Python static analysis tool is specifically designed to detect security vulnerabilities such as hardcoded passwords, use of eval(), and insecure deserialization? A. Flake B. Pylint C. Bandit

usage, B105/B106 relate to hardcoded passwords, and B602 relates to subprocess with shell=True. Q5. What is a key limitation of static analysis tools like Bandit? A. They require the application to be running B. They cannot understand whether a flagged dangerous call is reachable from untrusted input C. They only work on Python 2 code D. They automatically fix all detected issues Answer: B Rationale: Bandit works file by file on syntax patterns and has no dataflow or reachability analysis. It flags potentially dangerous constructs regardless of whether an attacker can actually influence the inputs. This is why Bandit findings often require human review rather than automatic rejection. Q6. Which static analysis tool is most appropriate for enforcing PEP 8 style compliance and catching simple logical errors in a CI pipeline? A. Bandit B. Flake C. Coverage.py D. pdb Answer: B Rationale: Flake8 is designed for fast style and correctness checks, making it well suited to CI gates that enforce PEP 8 and catch undefined names or unused imports. Bandit focuses on security, Coverage.py measures test coverage, and pdb is an interactive debugger. Q7. Pylint differs from Flake8 primarily in that Pylint: A. Only checks for style violations B. Performs deeper semantic analysis including type inference and

design issues C. Is a security-focused scanner D. Is a code formatter Answer: B Rationale: Pylint analyzes the AST for logical errors, undefined variables, and refactoring suggestions, while Flake8 is a wrapper for style and simple logic errors. Neither is primarily a security scanner; Bandit is for security. Q8. Which tool should be used to check whether a Python project's dependencies contain known published vulnerabilities? A. Bandit B. Pylint C. Safety or pip-audit D. Flake Answer: C Rationale: Safety and pip-audit compare installed or declared dependencies against vulnerability databases. Bandit analyzes first- party source code, while Pylint and Flake8 are general-purpose linters. Q9. What is the purpose of a .bandit configuration file? A. To define which security tests to run or skip and to configure severity thresholds B. To store unit test results C. To configure the Python interpreter version D. To define logging handlers Answer: A Rationale: A .bandit file (or pyproject.toml configuration) allows teams to customize Bandit's behavior, including selecting or excluding tests and setting severity/confidence thresholds.

imports are F401, line length is E501 (Pycodestyle), and eval() usage is a Bandit finding (B307). Q13. A CI job runs bandit -r app/. What does -r instruct Bandit to do? A. Report only high-severity issues B. Recursively scan directories under app/ C. Run in remediation mode D. Restrict scanning to a single file Answer: B Rationale: The -r flag instructs Bandit to recursively scan directories under the specified path. Q14. What is the difference between a static analysis "error" and a "warning"? A. Errors always indicate exploitable vulnerabilities; warnings never do B. Errors generally indicate definite problems, while warnings may indicate possible issues or style concerns that require judgment C. Warnings are always false positives D. There is no meaningful difference Answer: B Rationale: Static analyzers often distinguish severity. Errors tend to be definite issues (e.g., syntax or undefined names), while warnings can be stylistic, design-related, or context-dependent. Q15. A Flake8 report flags an E722 error in a Python file. What does this indicate? A. A line exceeds the maximum allowed length B. Use of a bare except: clause C. An unused import D. An undefined variable Answer: B Rationale: E722 is the Pycodestyle error code for a bare except: clause.

This is a security and reliability concern because it catches all exceptions, including system-exiting exceptions such as KeyboardInterrupt and SystemExit, and can mask critical errors.

Section 2: Python Application Logging (Q16–Q30)

Q16. A developer writes logger.info ("EVENT: login_attempt | ACTION: user=%s" % username) in a security-sensitive application. What is the preferred logging practice? A. Using string concatenation with + B. Using lazy %s formatting with arguments passed separately: logger.info ("EVENT: login_attempt | ACTION: user=%s", username) C. Using an f-string D. Writing the message to print() instead Answer: B Rationale: Passing arguments separately to the logging call allows the logging framework to defer string formatting until the message is actually emitted, improving performance and ensuring consistent handling. Eager formatting with % or f-strings constructs the string even if the log level is disabled. Q17. What is the primary security concern with using a bare except: clause in a Flask route that handles database operations? A. It improves error visibility B. It catches all exceptions, including system-exiting ones, and can silently suppress critical failures or security-relevant errors C. It prevents the application from logging errors D. It causes the application to crash immediately Answer: B

A. It makes logs larger B. It can lead to data breaches if log files are compromised or accessed by unauthorized personnel C. It slows down the application D. It has no security risk Answer: B Rationale: Logging sensitive data can lead to data breaches if log files are compromised. Best practice is to avoid logging sensitive information altogether or mask/redact it. Q21. A developer writes logger.info (f"User login: email={email}, password={password}"). What is the security issue? A. Using f-strings instead of % formatting B. Logging the plaintext password, which exposes it in log aggregation systems C. Using logger.info instead of logger.debug D. Including the email address Answer: B Rationale: The password should never be logged. Secrets exposed in log aggregation systems (ELK, Datadog, CloudWatch) can be accessed by unauthorized personnel. Q22. What is the correct approach when logging an API key for debugging purposes? A. Log the full API key B. Mask the sensitive parts (e.g., show only first 4 and last 4 characters) or omit it entirely C. Base64 encode the API key before logging D. Log the API key only at DEBUG level Answer: B Rationale: Sensitive information should never be logged directly. If you

must log information related to a sensitive field, log only what is necessary and ensure it's anonymized or masked. Q23. A developer wants to ensure that a security validation is enforced even under optimized Python execution. Which approach is appropriate? A. Use an assert statement with a descriptive message B. Use an explicit if statement that raises an exception when the condition is not met C. Use a comment indicating the required check D. Use a print() statement for warning Answer: B Rationale: Explicit conditional logic with exception raising is preserved under all optimization levels. This provides a reliable enforcement mechanism for security-critical validations, unlike assert statements which are stripped with -O. Q24. What does the logging.basicConfig() function do when called without arguments in a Python application? A. It disables all logging B. It configures the root logger with default settings, which may not include appropriate format or level for production C. It creates a new logger instance D. It writes logs to a file automatically Answer: B Rationale: Calling basicConfig() without proper format and level configuration may result in logs that lack essential metadata or use inappropriate severity levels. Proper configuration should include format and level. Q25. What is the security concern with calling logging.disable() in a production application?

aggregation (e.g., "show me all orders > $1000") in log management systems, unlike unstructured string logs. Q28. A developer wants to include a request ID in every log entry for a distributed system. Why is this important? A. It increases log volume B. It enables correlation of logs belonging to the same request across services C. It replaces the need for timestamps D. It is required by Python's logging module Answer: B Rationale: Including a request/correlation ID in every log entry allows operators to trace a single request across distributed services, which is essential for debugging and security investigation. Q29. When should a library module call logging.basicConfig() or set logger levels? A. Always, to ensure logs are captured B. Never; library consumers should configure logging, not the library C. Only when running in production D. Only when the library is used in a Flask application Answer: B Rationale: Libraries should use logging.getLogger(name) but should not call basicConfig or set levels, as this pollutes application logs and overrides the application's logging configuration. Q30. A Pytest test verifies that a log file contains an entry with the level WARNING when a deprecated feature is used. Which assertion is most appropriate? A. assert "WARNING" in caplog.text B. assert "DEBUG" in caplog.text C. assert len(caplog.records) == 0

D. assert caplog.records[0].levelname == "ERROR" Answer: A Rationale: caplog.text contains the formatted log output. Checking for "WARNING" in caplog.text verifies the expected level is present.

Section 3: Debugging & Exception Handling (Q31–Q40)

Q31. What is the primary advantage of using a debugger (e.g., pdb or IDE debugger) over print() statements? A. Debuggers are faster B. Debuggers allow interactive inspection of variables and program state without modifying the code C. Debuggers eliminate the need for testing D. Print statements cannot be used in Python Answer: B Rationale: Debuggers enable breakpoints and variable inspection without requiring code modifications. Print statements require manual removal and become unmanageable in large programs. Q32. A developer uses assert user.is _authenticated to enforce an authentication check in production code. Why is this practice insecure? A. assert statements cannot check object attributes B. Python's -O optimization flag removes assert statements from bytecode, silently disabling the security check C. assert statements always raise SystemExit D. assert statements cannot be used with boolean expressions Answer: B Rationale: When Python is run with the -O (optimize) flag, assert

C. ZeroDivisionError D. FileNotFoundError Answer: B Rationale: ValueError is raised when a function receives an argument of the correct type but an inappropriate value, such as int("hello"). Q36. A developer wants to validate user input before processing it. What is the recommended approach? A. Trust the input and handle errors later B. Validate input for type, range, and format before use, raising exceptions for invalid values C. Use eval() to parse the input D. Log the input and proceed Answer: B Rationale: The best error handling prevents errors. Validate input before use—check type, range, and format, and raise exceptions with clear messages for invalid values. Q37. What is the risk of catching an exception and silently passing without logging or handling it? A. It improves application performance B. It hides bugs and security-relevant failures, making diagnosis impossible C. It reduces log volume D. It is the recommended pattern Answer: B Rationale: Silently suppressing exceptions masks serious faults and prevents diagnosis. Exceptions should be handled appropriately, which includes logging at the appropriate level. Q38. A function raises a ValueError when given invalid input. Which Pytest construct is most appropriate to verify this behavior?

A. with pytest.raises(ValueError): B. assert function(input) == None C. try: function(input) except: pass D. assert isinstance(input, ValueError) Answer: A Rationale: pytest.raises is a context manager for asserting that code raises a specific exception. Q39. What is the purpose of a breakpoint in a debugger? A. To terminate the program B. To pause execution at a specific line so the developer can inspect variables and step through code C. To log a message D. To skip a function call Answer: B Rationale: Breakpoints allow developers to pause execution at specific points and inspect program state, which is a core debugging capability . Q40. Which HTTP status code typically indicates a redirect after a successful login in a Flask application? A. 200 B. 302 C. 404 D. 500 Answer: B Rationale: HTTP 302 Found indicates a temporary redirect. In a Flask login flow, successful authentication often redirects to a post-login dashboard.