Python Essentials: Requests, Pytest, JSONPath‑NG, Faker, Allure‑Pytest, PyHamcrest, PyMySQL, Redis, Logging, and ConfigParser
This article introduces ten essential Python libraries—Requests, Pytest, JSONPath‑NG, Faker, Allure‑Pytest, PyHamcrest, PyMySQL, Redis, Logging, and ConfigParser—explaining their purposes, key features, and providing ready‑to‑run code examples for HTTP requests, testing, data parsing, mock data generation, reporting, assertions, database access, caching, logging, and configuration management.
1. Requests – A simple HTTP client supporting GET, POST, PUT, DELETE and more. Features include an easy‑to‑use API, session management, file upload/download, automatic cookie handling and redirects. Example code shows how to send GET and POST requests, manage sessions, upload files and handle redirects.
import requests
response = requests.get('https://api.example.com/data')
print(f"Status Code: {response.status_code}")
print(f"Response Body: {response.text}")2. Pytest – A powerful testing framework with support for parameterized tests, fixtures, parallel execution and rich plugins. Sample tests demonstrate simple assertions, parameterization, fixture usage, output capture, and parallel execution via the pytest -n auto command.
def test_addition():
assert 1 + 1 == 2
import pytest
@pytest.mark.parametrize("input, expected", [(1,2), (2,4), (3,6)])
def test_double(input, expected):
assert input * 2 == expected3. JSONPath‑NG (or JSONPath‑RW) – Parses JSON data using expressive path syntax. Features include complex expressions, nested structure handling, and logical filters. Examples illustrate extracting titles from a book store, filtering by price, retrieving ages, using wildcards, and combining logical conditions.
from jsonpath_ng import parse
json_data = {"store": {"book": [{"title": "A"}, {"title": "B"}]}}
json_expr = parse('$.store.book[*].title')
titles = [m.value for m in json_expr.find(json_data)]
print(titles)4. Faker – Generates realistic fake data for testing, such as names, addresses, phone numbers, emails, and company names. Simple examples show how to create a Faker instance and print various fake fields.
from faker import Faker
fake = Faker()
print(fake.name())
print(fake.address())
print(fake.phone_number())
print(fake.email())
print(fake.company())5. Allure‑Pytest – Integrates with Pytest to produce attractive, detailed test reports with charts, multi‑environment support, and BDD‑style descriptions. Examples cover installation, adding Allure labels, recording steps, attaching files, and generating/opening the report.
pip install allure-pytest
import allure
@allure.feature('User Management')
@allure.story('Create New User')
def test_create_user():
pass6. PyHamcrest – Provides expressive matchers for clearer assertions. Includes built‑in matchers for equality, numeric comparisons, string containment, collection checks, and combinable matchers. Sample code demonstrates basic, numeric, string, collection, and composite matcher usage.
from hamcrest import *
assert_that(5, equal_to(5))
assert_that(10, greater_than(5))
assert_that('hello world', contains_string('world'))
assert_that([1,2,3], has_items(1,3))
assert_that({'name':'John','age':30}, all_of(has_entry('name','John'), has_entry('age',30)))7. PyMySQL (or mysql‑connector‑python) – Enables interaction with MySQL databases, supporting connection pools and transaction management. Examples cover creating a connection, executing queries, inserting, updating, and deleting records.
import pymysql
connection = pymysql.connect(host='localhost', user='user', password='passwd', database='db')
with connection.cursor() as cursor:
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"Database version: {version[0]}")8. Redis – Python client for Redis key‑value store, supporting strings, lists, sets, hashes, and pub/sub. Demonstrations include setting/getting a key, list operations, set operations, hash operations, and a simple publish/subscribe loop.
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
value = r.get('foo')
print(value.decode())9. Logging – Standard library for flexible logging with configurable levels, formats, handlers, and filters. Shows basic configuration, file logging, multiple handlers, custom formats, and a custom filter class.
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info('Application started')10. ConfigParser – Reads and writes INI‑style configuration files. Examples illustrate reading simple options, writing new sections, modifying existing values, checking for section/option existence, and using fallback defaults.
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
if config.has_section('database'):
config.set('database', 'timeout', '30')
with open('config.ini', 'w') as f:
config.write(f)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
