Prefer logging over print for production diagnostics because logging can be filtered, routed, and formatted centrally.
Question 2: What is unit testing in Python?
Ans
Unit testing verifies small pieces of code independently. Python's standard library includes unittest, and third-party frameworks such as pytest are also widely used.
Example
python
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 3, 5)
Important Point
Good unit tests isolate behavior and include meaningful edge cases.
Question 3: What is pytest?
Ans
pytest is a popular third-party Python testing framework known for simple test functions, fixtures, parametrization, and rich assertion reporting.
Example
python
def test_add():
assert 2 + 3 == 5
Important Point
pytest must be installed separately; follow the project's test dependencies and configuration.
Question 4: What is REST API consumption in Python?
Ans
Python applications can call HTTP APIs using libraries such as urllib from the standard library or third-party clients such as requests and httpx.
Example
python
# Example shape; actual HTTP client depends on project dependencies.
import requests
response = requests.get("https://example.com", timeout=10)
response.raise_for_status()
Important Point
Always use timeouts and handle status codes/errors deliberately when making network calls.
Question 5: What is SQL injection and how does Python prevent it?
Ans
SQL injection occurs when untrusted input is concatenated into SQL text. Python database APIs should use parameterized queries so values are bound separately from SQL syntax.
Example
python
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
Important Point
Placeholder syntax differs by database driver; never build SQL with string concatenation from untrusted input.
Question 6: What is monkey patching vs mocking?
Ans
Monkey patching changes an existing object or attribute at runtime. Mocking creates controlled test doubles that simulate dependencies and record interactions.
Example
python
from unittest.mock import Mock
service = Mock()
service.send.return_value = True
print(service.send("hello"))
Important Point
Mocks should verify meaningful behavior, not tightly couple tests to implementation details.