• Stars
    star
    418
  • Rank 103,620 (Top 3 %)
  • Language
    Python
  • License
    MIT License
  • Created over 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A pytest plugin that allows recording network interactions via VCR.py

pytest-recording

codecov Build Version Python versions License

A pytest plugin that records network interactions in your tests via VCR.py.

Features

  • Straightforward pytest.mark.vcr, that reflects VCR.use_cassettes API;
  • Combining multiple VCR cassettes;
  • Network access blocking;
  • The rewrite recording mode that rewrites cassettes from scratch.

Usage

import pytest
import requests

# cassettes/{module_name}/test_single.yaml will be used
@pytest.mark.vcr
def test_single():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'

# cassettes/{module_name}/example.yaml will be used
@pytest.mark.default_cassette("example.yaml")
@pytest.mark.vcr
def test_default():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'

# these cassettes will be used in addition to the default one
@pytest.mark.vcr("/path/to/ip.yaml", "/path/to/get.yaml")
def test_multiple():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'
    assert requests.get("http://httpbin.org/ip").text == '{"ip": true}'

Run your tests:

pytest --record-mode=once test_network.py

Default recording mode

pytest-recording uses the none VCR recording mode by default to prevent unintentional network requests. To allow them you need to pass a different recording mode (e.g. once) via the --record-mode CLI option to your test command. See more information about available recording modes in the official VCR documentation

Configuration

You can provide the recording configuration with the vcr_config fixture, which could be any scope - session, package, module, or function. It should return a dictionary that will be passed directly to VCR.use_cassettes under the hood.

import pytest

@pytest.fixture(scope="module")
def vcr_config():
    return {"filter_headers": ["authorization"]}

For more granular control you need to pass these keyword arguments to individual pytest.mark.vcr marks, and in this case all arguments will be merged into a single dictionary with the following priority (low -> high):

  • vcr_config fixture
  • all marks from the most broad scope ("session") to the most narrow one ("function")

Example:

import pytest

pytestmark = [pytest.mark.vcr(ignore_localhost=True)]

@pytest.fixture(scope="module")
def vcr_config():
    return {"filter_headers": ["authorization"]}

@pytest.mark.vcr(filter_headers=[])
def test_one():
    ...

@pytest.mark.vcr(filter_query_parameters=["api_key"])
def test_two():
    ...

Resulting VCR configs for each test:

  • test_one - {"ignore_localhost": True, "filter_headers": []}
  • test_two - {"ignore_localhost": True, "filter_headers": ["authorization"], "filter_query_parameters": ["api_key"]}

You can get access to the used VCR instance via pytest_recording_configure hook. It might be useful for registering custom matchers, persisters, etc.:

# conftest.py

def jurassic_matcher(r1, r2):
    assert r1.uri == r2.uri and "JURASSIC PARK" in r1.body, \
        "required string (JURASSIC PARK) not found in request body"

def pytest_recording_configure(config, vcr):
    vcr.register_matcher("jurassic", jurassic_matcher)

You can disable the VCR.py integration entirely by passing the --disable-recording CLI option.

Rewrite record mode

It is possible to rewrite a cassette from scratch and not extend it with new entries as it works now with the all record mode from VCR.py.

However, it will rewrite only the default cassette and won't touch extra cassettes.

import pytest

@pytest.fixture(scope="module")
def vcr_config():
    return {"record_mode": "rewrite"}

Or via command-line option:

$ pytest --record-mode=rewrite tests/

Blocking network access

To have more confidence that your tests will not go over the wire, you can block it with pytest.mark.block_network mark:

import pytest
import requests

@pytest.mark.block_network
def test_multiple():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'

...
# in case of access
RuntimeError: Network is disabled

Besides marks, the network access could be blocked globally with --block-network command-line option.

However, if VCR.py recording is enabled, the network is not blocked for tests with pytest.mark.vcr.

Example:

import pytest
import requests

@pytest.mark.vcr
def test_multiple():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'

Run pytest:

$ pytest --record-mode=once --block-network tests/

The network blocking feature supports socket-based transports and pycurl.

It is possible to allow access to specified hosts during network blocking:

import pytest
import requests

@pytest.mark.block_network(allowed_hosts=["httpbin.*"])
def test_access():
    assert requests.get("http://httpbin.org/get").text == '{"get": true}'
    with pytest.raises(RuntimeError, match=r"^Network is disabled$"):
        requests.get("http://example.com")

Or via command-line option:

$ pytest --record-mode=once --block-network --allowed-hosts=httpbin.*,localhost tests/

Or via vcr_config fixture:

import pytest

@pytest.fixture(autouse=True)
def vcr_config():
    return {"allowed_hosts": ["httpbin.*"]}

Additional resources

Looking for more examples? Check out this article about pytest-recording.

Contributing

To run the tests:

$ tox -p all

For more information, take a look at our contributing guide

Python support

Pytest-recording supports:

  • CPython 3.7, 3.8, 3.9, 3.10 and 3.11
  • PyPy 7 (3.6)

License

The code in this project is licensed under MIT license. By contributing to pytest-recording, you agree that your contributions will be licensed under its MIT license.

More Repositories

1

orbit

React components of open-source Orbit design system by Kiwi.com
TypeScript
1,388
star
2

navigation-compose-typed

Type-safe arguments for Jetpack Navigation Compose using Kotlinx.Serialization
Kotlin
217
star
3

margarita

[not actively maintained] Mobile and Web application implementing Kiwi.com Tequila API
JavaScript
208
star
4

orbit-compose

Android Jetpack Compose components of open-source Orbit design system by Kiwi.com.
Kotlin
144
star
5

mobile

📲 Kiwi.com mobile app written in React Native
JavaScript
140
star
6

orbit-swiftui

Kiwi.com Orbit design system library
Swift
131
star
7

structlog-sentry

Sentry integration for structlog
Python
99
star
8

crane

⬆ A GitLab CI ready image to upgrade services in Rancher
Python
96
star
9

the-zoo

🐒 A service registry for humans
Python
93
star
10

gitlab-unfurly

Serverless Slack bot for unfurling GitLab URLs.
Python
39
star
11

refined-gitlab

🛠 WIP 🛠 Chrome extension that enhances GitLab
JavaScript
32
star
12

orbit-design-tokens-archived

Design tokens store visual design attributes. They help us make our UI more consistent and consistent and support custom theming.
HTML
28
star
13

konfetti

Python configuration management system with an intuitive API
Python
27
star
14

dockerfiles

🐳 Collection of dockerfiles and automated docker hub builds
Dockerfile
27
star
15

monorepo-utils

🔧 Helpful functions to manage monorepos (using Yarn Workspaces)
JavaScript
26
star
16

react-native-reverse-geocode

Kotlin
25
star
17

contessa

Easy way to define, execute and store quality rules for your data.
Python
18
star
18

pg2avro

Utility generating avro files from postgres
Python
17
star
19

universal-components

Component Library for React Native, Expo and React applications
JavaScript
16
star
20

travelling-salesman

Rules for Kiwi.com travelling salesman competition
Python
15
star
21

python-weekend-entry-task

Entry task assignment for python weekend | https://pythonweekend.cz/
15
star
22

flask-ninja

Python
14
star
23

nitrolib

This is a mirror of https://gitlab.skypicker.com/frontend/nitrolib where y'all have no access 😽
JavaScript
13
star
24

fetch

🍒 Production ready fetch function with advanced capabilities like retries with delay and request cancellation after timeout
JavaScript
13
star
25

monorepo-shipit

Monorepo 👉 many repos Git exporter
JavaScript
12
star
26

smart-faq

Smart FAQ ⚠️INACTIVE → moved to internal GitLab ⚠️
JavaScript
11
star
27

easycql

Generate code for faster unmarshalling with gocql
Go
10
star
28

request-session

Python HTTP requests on steroids 💪
Python
10
star
29

relay

🚄 Opinionated Relay wrapper used at Kiwi.com
JavaScript
9
star
30

phoenix

Outage announcement integration with slack
Python
9
star
31

terraform-aws-nfs

🔧 NFS on AWS using ZFS, using ephemeral NVMe disks for L2ARC and RAID1 EBS storage
Shell
9
star
32

xssable

A vulnerable blogging platform used to demonstrate XSS vulnerabilities.
HTML
9
star
33

terraform-provider-montecarlo

This open-source Terraform provider enables users to seamlessly integrate the Monte Carlo data reliabillity platform into their infrastructure as a code (IaC) workflows.
Go
9
star
34

terraform-google-cloudfunctions

Terraform module for Google Cloud Functions
HCL
8
star
35

weekendfe

JS Weekend frontend site exercise
JavaScript
7
star
36

k8s-vault-operator

Go
7
star
37

kiwicom-python

🛠 WIP Internship project. Kiwi.com API wrapper
Python
7
star
38

starpicker

A tool that periodically checks sites for feedback about an entity and posts the findings to Slack.
Python
6
star
39

requests-iap

Python requests AuthClass authenticating HTTP requests to OIDC-authenticated resources (Cloud Identity-Aware Proxy)
Python
6
star
40

docsify-lunr-search

Search plugin for docsify.js which uses https://lunrjs.com/
JavaScript
5
star
41

stranger-strings

Web app for localisation analysing
Vue
5
star
42

catboost-cxx

OSS implementation of Yandex CatBoost model applier
C++
5
star
43

httpenv

📞 A service serving environment variables over HTTP
Python
5
star
44

Paper-Plane

TypeScript
5
star
45

eslint-plugin-relay-imports

JavaScript
4
star
46

eslint-plugin-kiwicom

JavaScript
4
star
47

wkshp-bucket-list-travel-app

Workshop in Budapest on 23/05/2019
JavaScript
4
star
48

graphql-bc-checker

🚦 Detect breaking changes in GraphQL schema with ability to log these changes.
JavaScript
4
star
49

pytest-catch-server

Pytest plugin with server fixture for catching HTTP requests.
Python
3
star
50

iwant-bot

🛠 WIP Internship project
Python
3
star
51

glenv

With direnv it will automatically export env. variables directly from GitLab
Go
3
star
52

kiwi-cache

Python
3
star
53

terraform-aws-rds-alarms

HCL
3
star
54

jsweekend

Project for attendees of https://jsweekend.cz
JavaScript
3
star
55

terraform-aws-rds-core

HCL
3
star
56

graphql-resolve-wrapper

Utility which enables to wrap GraphQL resolvers with your custom functions
JavaScript
3
star
57

fakesimdjson

Fallback to build simdjson-go tape using only encoding/json
Go
2
star
58

kiwi-json

Python
2
star
59

kiwi-structlog-config

Structlog configuration
Python
2
star
60

kiwi-platform-py

Company standards as code for Kiwi.com. Intended for use in Kiwi.com's internal Python projects.
Python
2
star
61

faqstorer

Python
2
star
62

terraform-vault-project

Vault resources for Gitlab project.
HCL
2
star
63

email-on-acid-sdk

Php sdk for email testing service Email on Acid
PHP
2
star
64

graphql-optics

📡 Monitoring tool for GraphQL servers and proxies
JavaScript
2
star
65

mlweekend

materials and entry task for intensive weekend course of machine learning
2
star
66

orbit-landing

JavaScript
2
star
67

orbit-playroom

Playroom allows you to design in the browser with orbit-components and support of JSX. You can easily share your code with anyone through a link, or open an example from orbit.kiwi.
JavaScript
2
star
68

gcp-api-enabler

Google Cloud Function that enables stated API's for newly created projects.
Python
2
star
69

vault2env-js

🔐 Utility to help us fetching ENV variables from Vault automatically
JavaScript
2
star
70

stopovers

Landing pages for stopover cities
JavaScript
2
star
71

terraform-kubernetes-elasticsearch

Elasticsearch module for Kubernetes based on elastic Helm charts
Python
2
star
72

eslint-config-kiwicom

💅 Eslint configuration for JS used at Kiwi.com.
JavaScript
2
star
73

terraform-kubernetes-namespace

HCL
2
star
74

summer-camp-live-map

JavaScript
1
star
75

graphql-global-id

Utility to manage ID fields in GraphQL correctly.
JavaScript
1
star
76

eslint-plugin-relay-fragments

ESLint plugin to keep your relay fragment components simple.
JavaScript
1
star
77

eslint-plugin-graphql-fragments

ESLint plugin to keep your GraphQL fragment components simple.
JavaScript
1
star
78

terraform-google-firestore

terraform module for the firestore projects
HCL
1
star
79

python-weekend-xmas-task

Entry task assignment for python weekend in Prague, 10 – 12 December 2021 | https://pythonweekend.cz/
1
star
80

orbit-swiftui-testing

Tests for the orbit-swiftui repository
Swift
1
star
81

travel-hack

A starter for hacking with @kiwicom/orbit-components and @kiwicom/relay
JavaScript
1
star
82

eslint-config-kiwicom-cypress

JavaScript
1
star
83

calendar-ux-test

New Calendar prototype for UX testing
JavaScript
1
star
84

hypothesis-jsonschema-unfit

Generate JSON data that does NOT match the given JSON schema
Python
1
star
85

terraform-google-cloudsql-core-postgresql

HCL
1
star
86

js-iam-middleware

Middleware to validate IAP JWT.
TypeScript
1
star
87

terraform-datadog-aws-lb-alarms

HCL
1
star
88

eslint-config-nitro

(DEPRECATED) ESlint config 🔥
JavaScript
1
star
89

terraform-gitlab-project-cluster

HCL
1
star
90

terraform-provider-scylla

Go
1
star
91

babel-preset-kiwicom

💈 Babel preset for JS used at Kiwi.com
JavaScript
1
star
92

terraform-aws-ftp-transfer-user

HCL
1
star
93

stranger-strings-sample-data

Sample data for https://github.com/kiwicom/stranger-strings
1
star
94

sourcelift

🏋 The source code powering kiwi.com/sourcelift
JavaScript
1
star
95

loopbind

🛠️ CLI tool to easily bind localhost network interface with additional IP and ensure matching record in /etc/hosts.
PHP
1
star
96

eslint-plugin-orbit-components

Linting rules for the best usage of @kiwicom/orbit-components
JavaScript
1
star