
















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!

















A+ VERIFIED
Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded
108
QUESTIONS
1
SECTIONS
108
RATIONALES
WHAT THIS COVERS
01 Software Security and Testing (Python)
02 Python logging configuration
03 Assertion
04 Exception handling
05 Static code analysis with tools such as Bandit
06 Unit/integration testing practices aligned with OWASP Top 10 (2021/2025)
ABOUT THIS ASSESSMENT This performance assessment exam evaluates secure coding, Python logging configuration, assertion and exception handling, static code analysis with tools such as Bandit and pylint, and unit/integration testing practices aligned with OWASP Top 10 (2021/2025) and ISTQB foundational concepts. Questions require multi-step reasoning about real-world security defects, test design, and remediation.
A. Using logging.basicConfig with default Formatter and writing raw user input directly. B. Setting a custom Formatter that sanitizes newline and control characters in messages. C. Increasing log level to CRITICAL to reduce volume of untrusted input logged. D. Redirecting logs to sys.stderr without any formatting to avoid parsing issues. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Log injection occurs when untrusted input containing newlines or control characters forges log entries; a custom Formatter that escapes or strips these characters neutralizes the attack. BasicConfig with raw input, raising levels, or redirecting streams does not sanitize content and therefore fails to prevent injection.
A. Set root logger to DEBUG and filter at the handler level using a regex for passwords. B. Use a custom Formatter that redacts fields and set level to INFO with structured JSON output. C. Disable all logging in production and rely on print statements for error tracking. D. Log all request data at WARNING level to ensure visibility without debug overhead. Answer: B [Concept: Software Security and Testing (Python)] Rationale: A custom Formatter with redaction and INFO-level structured logs balances security and debuggability. Option A risks leakage if filters fail; C loses observability; D still logs sensitive data at a high level.
A. To improve performance by reducing exception handling overhead. B. To allow callers to catch specific error types and handle them appropriately. C. To automatically log all exceptions to a file. D. To enforce type checking at runtime. Answer: B [Concept: Software Security and Testing (Python)] Rationale: A custom hierarchy enables granular exception handling by callers, improving error management. A is false (performance is not the goal); C requires explicit logging; D is unrelated to type checking.
A. Pylint analyzes style and some errors, not taint-based security flows; Bandit or Semgrep is needed. B. Pylint must be run with --disable=all to enable security checks. C. The pipeline should use flake8 instead because it detects injection. D. SQL injection cannot be detected by any static analyzer. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Pylint focuses on code quality and limited error patterns, not data-flow taint analysis for injection. Security-focused tools like Bandit or Semgrep perform taint tracking; flake8 is style-oriented, and injection is statically detectable with the right tool.
A. Flask disables assert statements automatically. B. Python's -O flag removes asserts, bypassing the authorization check. C. Assertions cannot evaluate boolean expressions. D. Assert raises HTTP 403 by default. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Under optimization (-O), Python strips assert statements, so authorization checks silently disappear, creating a bypass. Flask does not disable asserts (A), asserts evaluate booleans fine (C), and assert raises AssertionError, not HTTP 403 (D).
A. Use parameterized queries with placeholders and pass values separately. B. Escape single quotes in user input before concatenation. C. Switch to an ORM without changing query logic. D. Suppress the warning with # nosec after manual review. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Parameterized queries ensure that user input is treated as data, not executable code, preventing SQL injection. Escaping is error-prone, ORMs can still be misused, and suppressing the warning without fixing the root cause leaves the vulnerability.
A. When run with python -O, since assertions are stripped and validation is skipped. B. When run under pytest, since pytest rewrites assertions into exceptions. C. When run with PYTHONOPTIMIZE unset, since assertions then execute twice. D. When run under mypy, since type checking removes assert statements. Answer: A [Concept: Software Security and Testing (Python)] Rationale: The -O flag and PYTHONOPTIMIZE set debug to False, causing the interpreter to omit assert statements entirely, so security-relevant checks silently vanish. Pytest rewriting, mypy, and normal execution do not remove assertions; assertions should never enforce user-input validation.
A. Enable only E501 line length and ignore all security-related codes. B. Integrate bandit via flake8-bandit and fail the build on high-severity findings. C. Use flake8 with --exit-zero to avoid blocking merges. D. Rely on developer code review alone without automated linting. Answer: B [Concept: Software Security and Testing (Python)] Rationale: flake8-bandit brings security checks into linting and failing on high severity enforces standards. Ignoring security codes (A) defeats the purpose, --exit-zero (C) never blocks, and manual review alone (D) is inconsistent and misses issues.
A. Line coverage is sufficient; the defect must be in the test runner. B. Coverage measures executed lines, not branch or condition outcomes, so uncovered paths remain. C. The suite used unittest instead of pytest, which invalidates coverage. D. 100% coverage guarantees correctness only when mutation testing is disabled. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Line coverage counts executed statements, not whether every branch or boolean condition was exercised, so an unauthorized branch can remain untested. The framework choice is irrelevant, coverage never guarantees correctness, and mutation testing is a complementary technique rather than a validity switch.
A. Line coverage only. B. Branch coverage (--branch). C. Statement coverage with --omit. D. Path coverage enabled by default. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Branch coverage tracks both the taken and not-taken outcomes of each conditional, revealing untested False paths that line coverage misses. Line coverage only records executed statements, --omit excludes files rather than changing measurement, and coverage.py does not implement full path coverage.
A. Assertions raise AssertionError, which is not a subclass of Exception. B. Python removes assert statements when run with the -O optimization flag. C. Assertions cannot reference variables from enclosing function scope. D. AssertionError bypasses all configured logging handlers by default. Answer: B [Concept: Software Security and Testing (Python)] Rationale: The -O (and -OO) flag strips assert statements at compile time, so any security check implemented solely via assert silently disappears in optimized deployments. AssertionError is an Exception subclass, assertions can access local scope, and logging behavior is unrelated to why assertions are unsafe for enforcement.
A. Use of random.random() to generate a password reset token. B. Use of subprocess with shell=True on user input. C. Use of pickle.loads on untrusted network data. D. Use of eval() on a configuration string. Answer: A [Concept: Software Security and Testing (Python)] Rationale: random.random is a non-cryptographic PRNG, so tokens are predictable, a canonical A02 cryptographic failure; secrets.token_urlsafe is the fix. shell=True and eval map to injection, and pickle.loads maps to insecure deserialization, so they answer different categories.
A. Increased CPU consumption from stack unwinding. B. Exposure of sensitive information such as credentials or PII in logs. C. Loss of log ordering due to asynchronous handlers. D. Reduced effectiveness of log rotation policies. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Tracebacks and exception messages can embed secrets, tokens, or personal data from user input, creating a sensitive-information exposure risk (OWASP A09/A02). CPU, ordering, and rotation concerns are operational but not the primary security risk of logging tracebacks.
A. Assertions are stripped in optimized mode, disabling the check. B. Assertions cannot call methods. C. Assertions raise exceptions that crash the app. D. Assertions are not thread-safe. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Using assert for authorization is dangerous because assertions are removed when Python runs with -O, so the check is bypassed entirely. Assertions can call methods and raise exceptions, but the critical flaw is their removal in optimized mode.
A. Raise the log level to ERROR and attach a redaction filter to the handler. B. Switch the handler to StreamHandler(sys.stdout). C. Set propagate=False on the root logger. D. Increase the formatter's datefmt precision. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Raising the level reduces verbosity and a handler-level redaction filter removes tokens from emitted records, directly limiting exposure. Changing handler type (B), disabling propagation (C), or altering date format (D) does not redact secrets and may even broaden exposure.
A. if not isinstance(x, int): raise TypeError() B. assert isinstance(x, int), 'x must be int' C. try: int(x) except ValueError: raise D. if x is None: raise ValueError('missing') Answer: B [Concept: Software Security and Testing (Python)] Rationale: Assertions are stripped when Python runs with -O, so security or validation logic in an assert disappears in optimized mode. The other options use explicit raises that persist regardless of optimization flags.
A. Wrap the call in a try/except and log the exception. B. Replace with subprocess.call(shlex.split(cmd), shell=False) using a validated argument list. C. Add a # nosec comment with a justification. D. Run the subprocess under a lower-privileged user account only. Answer: B [Concept: Software Security and Testing (Python)] Rationale: shell=True enables shell metacharacter injection; passing a validated argument list with shell=False eliminates the shell interpretation. Suppressing the finding or merely lowering privileges does not remove the injection vector, and try/except only handles errors after exploitation.
A. Test doubles should replace external dependencies in unit tests, while integration tests verify real contracts. B. Integration tests should always mock to ensure determinism. C. Unit tests must use the network to be realistic. D. Mocking is only appropriate for database calls, not HTTP. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Unit tests isolate logic by mocking external I/O, whereas integration tests validate real interactions and contracts. Mocking everything in integration tests defeats their purpose, and unit tests should not depend on the network.
A. Suppress the finding with # nosec and document the risk acceptance. B. Convert the query to an f-string to improve readability and performance. C. Use parameterized queries with the DB-API execute() placeholders. D. Escape single quotes manually before concatenating user input. Answer: C [Concept: Software Security and Testing (Python)] Rationale: Bandit B608 detects SQL built by string formatting/concatenation; the canonical fix is parameterized queries, which separate code from data and prevent injection. Suppressing the finding, using f-strings, or manual quote escaping leaves injection risk and does not satisfy secure coding standards.
A. Defect density per thousand lines of code. B. Mean time to detect (MTTD). C. Remediation rate (closed findings / total findings). D. Test coverage percentage. Answer: C [Concept: Software Security and Testing (Python)] Rationale: Remediation rate directly expresses the fraction of findings that have been fixed, which is the clearest indicator of remediation progress. Defect density measures concentration, MTTD measures detection speed, and test coverage measures code exercised, not vulnerabilities resolved.
A. Assertions are always executed, causing performance degradation. B. Assertions can be disabled with the -O flag, removing validation in production. C. Assertions raise AssertionError, which is not catchable by except blocks. D. Assertions cannot check complex conditions, limiting validation scope. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Python's -O flag strips assert statements, so validation is skipped in optimized mode. A is false (asserts are removed, not always run); C is false (AssertionError is catchable); D is false (asserts can check any expression).
A. Run all tools on every commit and block merges on any finding. B. Run only on a nightly schedule and report results via email. C. Configure tools to fail the build only on high-severity findings, with baseline suppression. D. Disable static analysis for hotfix branches to speed deployment. Answer: C [Concept: Software Security and Testing (Python)] Rationale: Failing only on high-severity issues with a baseline for known false positives reduces noise and focuses on critical risks, maintaining productivity. Blocking on any finding causes alert fatigue, nightly-only delays feedback, and disabling for hotfixes introduces risk.
A. A01 Broken Access Control B. A03 Injection C. A05 Security Misconfiguration D. A08 Software and Data Integrity Failures Answer: B [Concept: Software Security and Testing (Python)] Rationale: String-built SQL with untrusted input is the canonical Injection (A03) example; parameterized queries are the fix. Access control, misconfiguration, and integrity failures describe different vulnerability classes.
A. Log raw input at DEBUG level only. B. Sanitize or encode newline and control characters before logging. C. Use print() instead of the logging module. D. Disable all logging in production. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Log injection occurs when attacker-controlled newlines/control characters forge log entries; sanitizing or encoding them neutralizes the attack. Log level, print(), or disabling logging do not address the root cause.
A. Using assert to validate internal invariants that should never fail. B. Using assert to enforce user input validation before processing. C. Using assert in unit tests to verify expected outcomes. D. Using assert to check preconditions in private helper functions. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Python's assert statements are removed when the interpreter runs with the -O (optimize) flag, so any security checks implemented via assert can be silently bypassed in production. User input validation must use explicit conditionals and exceptions, not assert. The other uses are acceptable because they are either internal invariants or test-only checks.
A. basicConfig only applies to named loggers, not the root logger. B. basicConfig is a no-op once the root logger already has handlers. C. basicConfig requires a FileHandler argument to take effect. D. basicConfig raises an exception that is swallowed by logging. Answer: B [Concept: Software Security and Testing (Python)] Rationale: basicConfig() configures the root logger only if it has no handlers; subsequent calls are effectively ignored unless force=True (Python 3.8+) is passed. It does apply to the root logger and does not require a FileHandler, so A and C are wrong; it does not raise a swallowed exception, so D is wrong.
A. Move the import inside the function so it loads only when needed. B. Add the dependency to requirements with a pinned hash. C. Wrap the import in try/except ImportError and continue silently. D. Vendor the dependency into the repository to control its code. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Deferring the import limits when privileged or rarely used code is loaded, shrinking the window and surface for exploitation, consistent with least-privilege design. Pinning, silent fallbacks, and vendoring affect supply-chain hygiene but do not reduce runtime exposure of the import.
A. Use of assert statements (B101). B. Hardcoded password string (B105). C. Import of the subprocess module (B404). D. Use of the random module (B311). Answer: B [Concept: Software Security and Testing (Python)] Rationale: Bandit flags hardcoded passwords (B105) as a high-severity issue because they expose credentials in source code. B (assert used) is low severity, B404 (subprocess import) is low severity, and B311 (random) is low severity for non-cryptographic use. Thus B105 is the most severe among the options.
A. self.assertTrue(False) inside a try block. B. self.assertRaises(ValueError) as a context manager around the call. C. A bare try/except ValueError: pass around the call. D. self.assertEqual(func(), None) after invoking the function. Answer: B [Concept: Software Security and Testing (Python)] Rationale: assertRaises as a context manager fails the test if the expected exception is not raised, eliminating the false positive. A bare try/except swallows the absence of the exception, assertTrue(False) is unrelated, and asserting a return value does not check exception behavior.
A. cursor.execute("SELECT * FROM t WHERE id = '%s'" % user_id) B. cursor.execute("SELECT * FROM t WHERE id = ?", (user_id,)) C. cursor.execute(f"SELECT * FROM t WHERE id = {user_id}") D. cursor.execute("SELECT * FROM t WHERE id = '" + user_id + "'") Answer: B [Concept: Software Security and Testing (Python)] Rationale: Parameterized queries with placeholders and a parameter tuple let the driver safely quote values, preventing SQL injection. String formatting (A), f-strings (C), and concatenation (D) embed untrusted input directly into SQL text and remain injectable.
A. Use a StreamHandler with default formatting to stderr. B. Use a RotatingFileHandler with a custom Formatter that escapes newline characters. C. Use a SysLogHandler with the default Formatter. D. Use a MemoryHandler with a large buffer capacity. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Log injection occurs when untrusted input containing newlines or control characters is written to logs, allowing attackers to forge log entries. A custom Formatter that escapes newline characters (e.g., replacing '\n' with '\n') neutralizes this risk. The other handlers do not inherently sanitize log messages, so they remain vulnerable.
A. Setting propagate to False on the child logger. B. Setting disable_existing_loggers to True. C. Assigning a filters list to the root logger. D. Configuring the handler's level to NOTSET. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Setting propagate to False on a child logger stops records from bubbling to ancestor handlers, preventing duplicate emission when both child and root handlers exist. disable_existing_loggers affects pre-existing loggers, not propagation; filters do not block propagation; and NOTSET on a handler inherits the logger's effective level rather than preventing duplication.
A. format: '%(message)s' with no sanitization. B. A custom Formatter that escapes CR/LF and control characters in the message before formatting. C. Setting datefmt to ISO 8601. D. Using %(asctime)s %(levelname)s %(message)s. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Log injection occurs when untrusted input containing CR/LF forges log entries; a custom Formatter that escapes control characters neutralizes this. Standard format strings and date formats do not sanitize message content.
A. Prefix the command with 'sudo' to restrict privileges. B. Wrap the call in try/except to suppress errors. C. Pass a list of arguments with shell=False. D. Add a # nosec comment to silence Bandit. Answer: C [Concept: Software Security and Testing (Python)] Rationale: shell=True enables command injection; passing a list with shell=False avoids shell interpretation and preserves functionality. Suppressing with # nosec hides risk, sudo escalates it, and try/except does not remove the injection vector.
A. Sensitive data exposure through insecure logging, violating OWASP A09. B. Improper log level; passwords should be logged at DEBUG. C. Missing exception handling around the logging call. D. Use of INFO instead of WARNING for authentication events. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Logging credentials constitutes sensitive information exposure (OWASP A09: Security Logging and Monitoring Failures) because logs are widely readable and retained. Logging at DEBUG still exposes the secret, exception handling is unrelated, and the level choice for authentication events does not justify recording passwords.
A. patch('utils.validate') B. patch('module_under_test.validate') C. patch('builtins.validate') D. patch('validate') Answer: B [Concept: Software Security and Testing (Python)] Rationale: Because the name was imported into the module under test, patch must target where it is looked up-module_under_test.validate. Patching utils.validate (A) changes the original but not the already-bound reference. builtins.validate (C) and bare validate (D) are invalid targets.
A. Catch specific exceptions and log details internally, return a generic error message. B. Use a bare except: to catch all exceptions and return str(e). C. Let exceptions propagate to the web framework's default handler. D. Print the traceback to stdout and continue. Answer: A [Concept: Software Security and Testing (Python)] Rationale: Catching specific exceptions, logging details securely, and returning a generic message prevents information leakage while preserving diagnostics. Bare except and returning str(e) can expose sensitive details, and default handlers may show stack traces.
A. Call the function directly; environment variables are immutable during tests. B. Use unittest.mock.patch.dict(os.environ, {'SECRET_KEY': 'test'}) as a context manager. C. Set os.environ permanently in setUpClass and never restore it. D. Replace the function with a lambda that returns a hardcoded key. Answer: B [Concept: Software Security and Testing (Python)] Rationale: patch.dict temporarily modifies os.environ and restores it afterward, providing isolation and preventing test pollution. Direct calls depend on ambient state, permanent mutation leaks across tests, and replacing the function under test defeats the purpose of testing it.
A. B B. B C. B D. B Answer: A [Concept: Software Security and Testing (Python)] Rationale: Bandit B101 flags assert usage because assertions are stripped under -O, making them unreliable for security checks. B301 covers pickle deserialization, B602 covers shell=True subprocess calls, and B105 flags hardcoded passwords.
A. Increase the test timeout to accommodate slower CI clocks. B. Freeze time with a library like freezegun or inject a clock dependency. C. Assert on a range of acceptable dates instead of an exact value. D. Set the CI machine's TZ to the developer's local timezone. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Freezing time or injecting a controllable clock removes environmental nondeterminism and makes date logic deterministically testable. Timeouts address performance not correctness, range assertions mask defects, and forcing CI timezones merely hides the underlying coupling.
A. subprocess.run(['ls', user_input], shell=False) B. subprocess.run(f'ls {user_input}', shell=True) C. os.listdir(user_input) D. shutil.copy(user_input, '/tmp/backup') Answer: B [Concept: Software Security and Testing (Python)] Rationale: Using shell=True with an f-string that incorporates user input allows shell metacharacters to be interpreted, enabling command injection. Option A passes arguments as a list with shell=False, which avoids shell interpretation. Options C and D do not invoke a shell and are not command injection vectors.
A. assertRaises(ValueError) as a context manager around the call. B. assertTrue(isinstance(result, ValueError)) after calling the function. C. assertRaisesRegex(ValueError, '.*') only if a message is expected. D. assertWarns(ValueError) to confirm the exception type. Answer: A [Concept: Software Security and Testing (Python)] Rationale: assertRaises used as a context manager executes the block and fails the test if the specified exception is not raised, which is the canonical pattern. assertTrue on a result cannot catch an exception that aborts execution, assertRaisesRegex requires a message pattern and is not the general form, and assertWarns checks warnings, not exceptions.
A. The developer's opinion of the tool's reputation. B. A screenshot of the IDE theme. C. Tool name, rule ID, file/line, severity, and remediation evidence. D. The total number of code comments. Answer: C [Concept: Software Security and Testing (Python)] Rationale: A defensible finding documents tool, rule, location, severity, and remediation proof so reviewers can verify closure. Opinions, IDE cosmetics, and comment counts do not substantiate the vulnerability or its fix.
A. Use assert for validating user-supplied input because it raises AssertionError. B. Use assert to enforce internal invariants, but never for input validation since -O strips asserts. C. Use assert for authentication checks because it is faster than explicit exceptions. D. Use assert in all security checks and disable optimization with PYTHONOPTIMIZE=0. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Python's -O flag removes assert statements, so asserts must not enforce security or input validation; they are only for internal invariants. Using assert for user input (A) or authentication (C) creates bypasses when optimized. Relying on PYTHONOPTIMIZE=0 (D) is fragile and not a secure design.
A. Set disable_existing_loggers to True. B. Use a QueueHandler with a QueueListener and a bounded queue with backpressure handling. C. Configure the root logger level to CRITICAL to reduce volume. D. Attach multiple FileHandler instances to the same file. Answer: B [Concept: Software Security and Testing (Python)] Rationale: QueueHandler with QueueListener offloads I/O to a separate thread, and a bounded queue with explicit backpressure prevents silent drops under load. Disabling loggers or raising levels discards records, and multiple handlers on one file cause contention.
A. Add '# nosec' to the line to suppress the finding. B. Replace the f-string with parameterized query placeholders and bound parameters. C. Wrap the query in a try/except and log the exception. D. Encode the f-string with base64 before execution. Answer: B [Concept: Software Security and Testing (Python)] Rationale: B608 indicates possible SQL injection from string-built queries; parameterized queries separate code from data and eliminate the vulnerability. Suppressing with nosec hides the risk, exception handling does not prevent injection, and base64 encoding is reversible and provides no security.
A. Relying solely on static analysis tools for vulnerability detection. B. Combining unit tests, integration tests, and security-focused code reviews. C. Performing penetration testing only after deployment. D. Using assertions for all input validation in production. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Defense in depth involves multiple layers of testing and review to catch different classes of issues. A is single-layer; C is too late; D is insecure because assertions can be disabled.
A. A try/except block with a boolean flag asserted afterward. B. pytest.raises(ValueError, match='invalid token') as context. C. A decorator @pytest.mark.xfail(raises=ValueError). D. assertRaisesRegex from unittest.TestCase without message check. Answer: B [Concept: Software Security and Testing (Python)] Rationale: pytest.raises with match asserts both the exception type and a regex on its message, the most precise negative-path check. Manual try/except flags are brittle, xfail tolerates failure rather than asserting it, and the unittest form here omits the message verification.
A. Broken access control B. Security logging and monitoring failures with sensitive data exposure C. Server-side request forgery D. Insecure deserialization Answer: B [Concept: Software Security and Testing (Python)] Rationale: Logging full request bodies can expose credentials and PII, aligning with OWASP's logging/monitoring failures and sensitive data exposure categories. Access control, SSRF, and deserialization are distinct risks not directly caused by verbose logging.
A. Mocks increase test execution time significantly. B. Mocks can hide integration issues by not testing real interactions. C. Mocks prevent the use of assertions in tests. D. Mocks are not compatible with pytest fixtures. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Over-mocking can create tests that pass despite real integration failures, reducing test effectiveness. A is false (mocks are fast); C is false (assertions work with mocks); D is false (they are compatible).
A. Use hashlib.sha256 with a static application-wide salt. B. Use bcrypt or argon2 with a unique per-user salt and appropriate work factor. C. Use hashlib.md5 with a random salt for speed. D. Store passwords encrypted with AES using a hardcoded key. Answer: B [Concept: Software Security and Testing (Python)] Rationale: OWASP recommends adaptive hashing such as bcrypt or Argon2 with unique salts and tuned work factors. SHA-256 with a static salt (A) is fast and vulnerable to rainbow tables. MD5 (C) is cryptographically broken, and hardcoded AES keys (D) are insecure.
A. Statement coverage only, since every line is counted equally. B. Branch coverage, which measures decision outcomes taken by tests. C. Cyclomatic complexity of the module under test. D. Number of assertions per test function. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Branch coverage records whether both true and false outcomes of each decision are exercised, which is essential for verifying authorization checks that may sit on one branch. Statement coverage can miss untested branches, complexity measures code structure, and assertion counts do not measure coverage.
A. Suppress B608 with # nosec and add input length limits. B. Escape single quotes manually before interpolation. C. Use parameterized queries with the DB-API placeholder style. D. Switch to .format() with named placeholders to avoid f-strings. Answer: C [Concept: Software Security and Testing (Python)] Rationale: B608 signals possible SQL injection from string-built queries; parameterized queries separate code from data and eliminate the taint path, satisfying Bandit and OWASP A03. nosec hides the finding, manual escaping is error-prone, and .format() remains string interpolation and still tainted.
A. Run flake8 with --exit-zero so all findings are reported without failing. B. Run bandit with -lll (high severity only) and fail the job on nonzero exit. C. Run pylint with --disable=all to suppress style and security messages. D. Run bandit with -s B101 to skip assert checks and ignore severity. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Bandit's -lll flag reports only high-severity issues, and its nonzero exit code on findings fails the CI job as required. --exit-zero never fails, disabling all pylint messages removes security checks, and skipping B101 does not filter by severity.
A. Assertions are removed when Python runs with the -O optimization flag. B. Assertions raise AssertionError which is not catchable. C. Assertions cannot check complex conditions. D. Assertions are slower than if-statements. Answer: A [Concept: Software Security and Testing (Python)] Rationale: When Python is run with -O (optimize), assert statements are stripped from the bytecode, so any validation relying on assertions is silently disabled, potentially allowing invalid input. Assertions are catchable, can check complex conditions, and performance is not the primary concern.
A. DEBUG B. INFO C. WARNING D. ERROR Answer: C [Concept: Software Security and Testing (Python)] Rationale: Failed login attempts are security-relevant events that are not errors in the application but warrant attention, making WARNING appropriate. DEBUG is too verbose, INFO may be lost in noise, and ERROR implies a malfunction rather than a security event.
A. Mark both tests with @pytest.mark.dependency to enforce order. B. Move shared state into module-level globals initialized once. C. Use a function-scoped fixture to construct fresh state per test. D. Run the suite with pytest -p no:randomly to fix ordering. Answer: C [Concept: Software Security and Testing (Python)] Rationale: Function-scoped fixtures isolate state so each test is independent, the ISTQB and pytest-recommended remedy for inter-test coupling. Dependency markers, shared globals, and disabling randomization entrench order dependence and mask flakiness rather than removing it.
A. @pytest.mark.parametrize B. @pytest.fixture(params=...) C. pytest.mark.skipif D. pytest.raises Answer: A [Concept: Software Security and Testing (Python)] Rationale: @pytest.mark.parametrize is specifically designed to run a test function multiple times with different argument sets. @pytest.fixture(params=...) parameterizes a fixture, not the test directly. skipif conditionally skips tests, and raises asserts exceptions.
A. Line coverage guarantees security correctness. B. Coverage measures executed lines, not input-space or branch conditions. C. Coverage tools cannot measure Python branches. D. SQL injection is undetectable by any testing method. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Statement coverage only confirms lines executed, not that security-relevant branches or malicious inputs were exercised; branch coverage and adversarial test cases are needed. Coverage does not guarantee security, tools can measure branches, and injection is testable.
A. Coverage guarantees security when combined with assertions. B. Line coverage measures execution, not input-space exploration or security properties. C. Static analysis is unnecessary once coverage is complete. D. Integration tests are always superior to unit tests for security. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Coverage only shows which lines executed, not whether adversarial inputs or security branches were tested. It does not guarantee security (A), does not replace static analysis (C), and does not make integration tests universally superior (D).
A. Log records will not be passed to ancestor loggers' handlers. B. Log records will be duplicated to all handlers. C. The logger will stop emitting any log records. D. The logger's level will be set to NOTSET. Answer: A [Concept: Software Security and Testing (Python)] Rationale: propagate=False prevents records from bubbling up to parent handlers, avoiding duplicate output. B is the opposite; C is false (records still handled by this logger); D is unrelated.
A. Run a single-threaded unit test with mocks. B. Stress-test with many concurrent threads and assert invariants post-execution. C. Increase the sleep interval to ensure ordering. D. Disable the GIL using sys.setswitchinterval(1.0). Answer: B [Concept: Software Security and Testing (Python)] Rationale: Race conditions manifest under concurrent execution, so stress testing with many threads and invariant assertions exposes them. Single-threaded mocks (A) cannot reveal races, adding sleeps (C) hides them, and sys.setswitchinterval(1.0) lengthens the switch interval rather than disabling the GIL (D).
A. Using os.path.join with a constant base directory and user filename. B. Passing user-controlled filename directly to open() without normalization. C. Serving files via a framework's static file handler with allowlist. D. Logging the requested filename at INFO level before opening. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Directly opening a user-controlled path without normalization or containment allows '../' sequences to escape the intended directory, the hallmark of path traversal. os.path.join alone does not prevent traversal if the user input is absolute, while allowlisted static handlers and logging are not traversal causes.
A. Use a custom Formatter that redacts fields like password and token before emission. B. Set the root logger level to DEBUG to capture all events for audit. C. Log full request bodies at INFO level to aid debugging. D. Rely on the default logging configuration without filters. Answer: A [Concept: Software Security and Testing (Python)] Rationale: A custom Formatter that redacts sensitive fields ensures that even if such data is passed to logging calls, it is masked before being written to handlers, directly preventing leakage. Setting DEBUG or logging full request bodies increases exposure, and the default configuration lacks redaction.
A. Set maxBytes and backupCount so old files rotate out after size limits. B. Use delay=True with mode='a' to defer file creation. C. Attach a StreamHandler to stderr instead of a file handler. D. Set the formatter to include %(created)f timestamps only. Answer: A [Concept: Software Security and Testing (Python)] Rationale: RotatingFileHandler rotates when maxBytes is reached and retains only backupCount files, bounding disk usage while keeping recent logs. delay and mode affect file opening, a StreamHandler writes to a stream rather than rotating files, and formatter fields do not control retention.
A. The assertion raises AssertionError with a different message. B. The assertion is stripped, so validation is silently skipped in optimized mode. C. The assertion executes twice, causing duplicate side effects. D. The assertion is converted into a warning rather than an error. Answer: B [Concept: Software Security and Testing (Python)] Rationale: Python's -O flag removes assert statements, so using assert for input validation means validation vanishes in optimized deployments. Assertions are for internal invariants, not runtime security checks; explicit exceptions must be used instead.
A. Cyclomatic complexity B. Code coverage percentage C. Halstead volume D. Maintainability index Answer: B [Concept: Software Security and Testing (Python)] Rationale: Code coverage measures the proportion of code exercised by tests, directly indicating how thoroughly the test suite covers the codebase. Cyclomatic complexity, Halstead volume, and maintainability index are code complexity metrics, not test thoroughness metrics.