
































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!

































Section 1: Static Code Analysis Question 1: 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 Correct Answer: B. To examine source code for defects, style violations, and security issues without running it 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, which is a separate concern. Question 2: 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 D. Black Correct Answer: C. Bandit Rationale: Bandit is a security-focused static analysis tool that walks the Python AST looking for known-dangerous constructs, including eval, exec, pickle deserialization, subprocess with shell=True, and hardcoded credentials. Each finding maps to a CWE identifier. Flake8 and Pylint are quality and style linters, not security linters. Black is a code formatter, not an analyzer. Question 3: Flake8 is a wrapper around which two principal tools? A. Bandit and Safety B. Pycodestyle and Pyflakes C. Pylint and Mypy D. Black and isort Correct Answer: B. Pycodestyle and Pyflakes Rationale: Flake8 combines Pycodestyle (which checks PEP 8 style conventions) and Pyflakes (which detects logical errors such as undefined names and unused imports). It can also integrate plugins, but its core is these two. Bandit, Pylint, Mypy, Black, and isort are separate tools with different purposes. Question 4: A developer runs Bandit and receives finding B301. What class of issue does this represent? A. Use of assert in production code B. Insecure use of pickle.loads() C. Hardcoded password in a configuration file
C. Coverage.py D. pdb Correct Answer: B. Flake 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. Question 7: Pylint differs from Flake8 primarily in that Pylint: A. Only checks security vulnerabilities B. Provides a broader rule set including design smells and a code quality score C. Is a runtime debugger D. Cannot be integrated into CI Correct Answer: B. Provides a broader rule set including design smells and a code quality score Rationale: Pylint checks style and errors but also evaluates design-level concerns such as too many arguments, duplicate code, and cyclomatic complexity, and it produces a scored report. Flake8 is faster and narrower. Neither is a dedicated security tool or a debugger, and both can run in CI. Question 8: A Bandit finding for subprocess.Popen(cmd, shell=True) is most closely associated with which vulnerability class? A. Cross-site scripting B. OS command injection C. SQL injection
D. Buffer overflow Correct Answer: B. OS command injection Rationale: Using shell=True passes the command string to the system shell, which can allow shell metacharacters to be interpreted if the command includes untrusted input. This creates an OS command injection risk (CWE-78). XSS and SQL injection involve different sinks, and buffer overflow is not the primary concern in Python. Question 9: What does the Bandit rule B101 flag? A. Use of assert statements B. Use of eval() C. Insecure temporary file creation D. Weak random number generation Correct Answer: A. Use of assert statements Rationale: Bandit flags assert statements because they can be stripped when Python runs with the - O optimization flag. If an assertion is being used for a security check, that check may disappear in optimized mode. eval() is covered by other rules (e.g., B307), and temporary files and random generation have separate rule identifiers. Question 10: Which command runs Flake8 on a Python file named app.py? A. flake8 app.py B. python flake8 app.py C. flake8 --run app.py D. flake8 app.py --execute
Correct Answer: A. A developer intentionally uses pickle to deserialize data from a trusted internal cache Rationale: Bandit flags pickle.loads() without tracing data origin. If the data comes exclusively from a trusted, integrity-protected internal cache and never from untrusted input, the finding is a false positive from a risk perspective. The other options describe genuine security weaknesses. Question 13: mypy is primarily used for: A. Runtime performance profiling B. Static type checking C. Security vulnerability scanning D. Code formatting Correct Answer: B. Static type checking Rationale: Mypy analyzes type annotations and reports type inconsistencies without executing the code. It is not a profiler, a security scanner, or a formatter. Question 14: Which of the following best describes “linting” in Python? A. Executing a program with a debugger attached B. Analyzing code for style, correctness, and potentially security issues without running it C. Compiling Python to machine code D. Measuring memory usage Correct Answer: B. Analyzing code for style, correctness, and potentially security issues without running it
Rationale: Linting is a form of static analysis focused on style, correctness, and—in tools like Bandit—security patterns. It does not involve debugging execution, compilation, or memory profiling. Question 15: A CI pipeline fails because Flake8 reports E501. What does this mean? A. A line exceeds the maximum allowed length B. A variable is undefined C. An import is unused D. A function has too many arguments Correct Answer: A. A line exceeds the maximum allowed length Rationale: E501 is the Pycodestyle error code for “line too long.” Undefined names are reported by Pyflakes (e.g., F821), unused imports by F401, and too many arguments by Pylint (R0913), not Flake8’s default rules. Question 16: 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 Correct Answer: C. Safety or pip-audit 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.
B. A line exceeding 79 characters C. Use of eval() on user input D. An undefined variable Correct Answer: C. Use of eval() on user input Rationale: Flake8’s core checks (Pycodestyle and Pyflakes) focus on style and correctness, not security sinks. eval() usage is a security concern flagged by Bandit (e.g., B307). Unused imports, line length, and undefined variables are within Flake8’s scope. Question 20: 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 Correct Answer: A. To define which security tests to run or skip and to configure severity thresholds 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. It does not store test results, interpreter settings, or logging configuration. Question 21: Which of the following best explains why Bandit flags assert statements in production code? A. Assertions are slower than if statements
B. Assertions can be removed when Python runs with optimization, potentially removing security checks C. Assertions cannot be used in functions D. Assertions always raise SystemExit Correct Answer: B. Assertions can be removed when Python runs with optimization, potentially removing security checks Rationale: Python’s - O flag strips assert statements. If an assertion is used to enforce a security-relevant condition, that enforcement disappears in optimized mode. The concern is not performance, syntax restrictions, or SystemExit. Question 22: A developer wants to suppress a specific Bandit finding on a single line. What is the recommended approach? A. Delete the line B. Add a # nosec comment on that line, with a justification C. Disable Bandit entirely D. Rewrite the code in another language Correct Answer: B. Add a # nosec comment on that line, with a justification Rationale: # nosec tells Bandit to skip the finding on that line. Best practice includes a justification so reviewers understand why the suppression is acceptable. Deleting the line, disabling the tool, or changing languages are disproportionate or incorrect responses. Question 23: What does the Pyflakes check F821 indicate? A. An unused import B. An undefined name
Correct Answer: B. Bandit findings in dependencies are often not actionable by the team, and dependency vulnerabilities should be tracked separately Rationale: Teams cannot directly fix third-party source code; dependency vulnerabilities are better managed through dependency scanners and update processes. Third-party code can contain vulnerabilities, Bandit can parse it, and no code is automatically secure. Question 26: 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 Correct Answer: B. Errors generally indicate definite problems, while warnings may indicate possible issues or style concerns that require judgment 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. Warnings are not automatically false positives, and errors are not always exploitable vulnerabilities. Question 27: 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
Correct Answer: B. Recursively scan directories under app/ Rationale: The - r flag tells Bandit to recurse into subdirectories. Severity filtering uses - ll or - lll, remediation is not a Bandit mode, and single-file scanning would omit - r. Question 28: Which of the following is an example of a design smell that Pylint might report? A. too-many-arguments (R0913) B. hardcoded-password (B105) C. pickle-loads (B301) D. line-too-long (E501) Correct Answer: A. too-many-arguments (R0913) Rationale: Pylint reports design-level issues such as too many arguments (R0913), duplicate code, and excessive complexity. B105 and B301 are Bandit security findings. E501 is a Pycodestyle/Flake8 line-length issue. Question 29: What is a key advantage of running static analysis in the IDE compared with running it only in CI? A. It catches issues while the developer is actively writing code, enabling immediate correction B. It replaces the need for CI C. It executes the application faster D. It automatically writes documentation Correct Answer: A. It catches issues while the developer is actively writing code, enabling immediate correction
Rationale: The logging module is part of Python’s standard library and provides loggers, handlers, formatters, and levels. log, logger, and syslog are not the standard library logging module (although syslog is a handler destination). Question 32: What are the five standard logging levels in Python, in increasing order of severity? A. TRACE, DEBUG, INFO, WARN, FATAL B. DEBUG, INFO, WARNING, ERROR, CRITICAL C. LOW, MEDIUM, HIGH, SEVERE, FATAL D. VERBOSE, DEBUG, NOTICE, ERROR, PANIC Correct Answer: B. DEBUG, INFO, WARNING, ERROR, CRITICAL Rationale: Python’s standard levels are DEBUG (10), INFO (20), WARNING (30), ERROR (40), and CRITICAL (50). TRACE and FATAL are not standard Python levels (FATAL is an alias for CRITICAL in some contexts, but the standard five-level progression is as listed). Question 33: What is the recommended way to create a logger in a Python module? A. logging.getLogger(name) B. logging.Logger() C. logging.root D. print() Correct Answer: A. logging.getLogger(name) Rationale: logging.getLogger(name) creates a module-level logger with a hierarchical name that reflects the module path. This supports per-module
filtering and avoids collisions. Directly instantiating Logger() bypasses the manager, logging.root is the root logger, and print() is not a logger. Question 34: A logger is configured at level WARNING. Which of the following calls will produce output? A. logger.debug("details") B. logger.info("status") C. logger.warning("disk almost full") D. logger.log(logging.DEBUG, "trace") Correct Answer: C. logger.warning("disk almost full") Rationale: A logger at WARNING processes messages at WARNING and above. DEBUG and INFO messages are below the threshold and are discarded. logger.log(logging.DEBUG, ...) is also below the threshold. Question 35: What is the role of a logging handler? A. To format log messages into strings B. To determine where log records are sent (e.g., console, file, socket) C. To create loggers D. To define the severity level of a message Correct Answer: B. To determine where log records are sent (e.g., console, file, socket) Rationale: Handlers route log records to destinations. Formatters render messages, loggers are created via getLogger, and severity levels are specified at the call site or configured on loggers/handlers.
Question 38: A developer writes logging.basicConfig(level=logging.INFO). What effect does this have? A. It configures the root logger to process INFO and higher-severity messages B. It creates a new logger named “basic” C. It sends all logs to a file named basic.log D. It disables all logging below CRITICAL Correct Answer: A. It configures the root logger to process INFO and higher- severity messages Rationale: basicConfig performs one-time configuration of the root logger, including setting the level. INFO and higher (WARNING, ERROR, CRITICAL) will be processed. It does not create a logger named “basic” or automatically create a file unless filename is specified. Question 39: Why is it important to avoid logging sensitive data such as passwords, session tokens, and personal health information? A. It slows down the application B. Logs are often stored, transmitted, and accessed with weaker controls than primary data stores, creating a data exposure risk C. Sensitive data cannot be represented as strings D. Python’s logging module rejects such data automatically Correct Answer: B. Logs are often stored, transmitted, and accessed with weaker controls than primary data stores, creating a data exposure risk Rationale: Logs may be shipped to central systems, retained for long periods, and viewed by operators. Logging secrets or sensitive personal data expands the attack surface and can violate compliance requirements. The concern is not performance, string representation, or automatic rejection by the module.
Question 40: What is log injection? A. A technique for compressing log files B. An attack in which untrusted input is written into logs and can forge entries or corrupt log analysis C. A method for rotating logs D. A feature of the logging module for injecting dependencies Correct Answer: B. An attack in which untrusted input is written into logs and can forge entries or corrupt log analysis Rationale: If untrusted input containing newlines or control characters is logged without sanitization, an attacker may be able to create fake log entries, confuse parsers, or obscure malicious activity. This is a log injection risk. The other options are unrelated to the security concept. Question 41: Which practice best mitigates log injection? A. Logging raw user input exactly as received B. Sanitizing or escaping untrusted values before including them in log messages C. Disabling logging entirely D. Logging only at CRITICAL level Correct Answer: B. Sanitizing or escaping untrusted values before including them in log messages Rationale: Sanitizing newlines and control characters, or using structured logging that encodes fields, prevents attackers from forging entries. Logging raw input enables injection. Disabling logging or reducing to CRITICAL sacrifices visibility without addressing the root cause.