Skip to content

Commit

Permalink
format
Browse files Browse the repository at this point in the history
  • Loading branch information
grizz committed Apr 29, 2024
1 parent 8173ac3 commit 03438da
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 34 deletions.
31 changes: 31 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
fail_fast: false
exclude: |
(?x)^(
tests/data/.*
)$
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-toml
- id: check-yaml
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.1.14
hooks:
# Run the linter.
- id: ruff
# removes imports for tests
exclude: tests/
args: [--fix]
# Run the formatter.
- id: ruff-format
- repo: local
hooks:
- id: pyupgrade
name: pyupgrade
entry: poetry run pyupgrade --py38-plus
language: python
types: [python]
pass_filenames: true
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ classifiers = [
"Development Status :: 5 - Production/Stable",
"Framework :: Pytest",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
40 changes: 19 additions & 21 deletions pytest_filedata/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@

from builtins import map
from builtins import object
import collections
from datetime import datetime
import json
Expand All @@ -24,17 +21,16 @@ def setup(base_dir, fixture_prefixes=None):

def json_hook(data):
date_keys = (
'last_change',
'last_reboot',
'last_reconfiguration',
)
"last_change",
"last_reboot",
"last_reconfiguration",
)
for key in date_keys:
if key in data:
data[key] = datetime.strptime(data[key], "%Y-%m-%dT%H:%M:%S")
return data



class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
Expand All @@ -55,20 +51,21 @@ def loads(data):
return json.loads(data, object_hook=json_hook)


class FileTestData(object):
""" object to hold file test data """
class FileTestData:
"""object to hold file test data"""

def __init__(self, inp=None, exp=None, name=None, path=None):
self.input = inp
self.expected = exp
self.name = name
self.path = path

def dumps(self, data):
""" dump data in configured output method """
"""dump data in configured output method"""
return dumps(data)

def loads(self, data):
""" load data in configured output method """
"""load data in configured output method"""
return loads(data)


Expand All @@ -87,25 +84,25 @@ def get_data(name):
Gets data from fixture name.
"""
data = collections.OrderedDict()
dirname = os.path.join(test_dir, *name.split('_'))
dirname = os.path.join(test_dir, *name.split("_"))

if not os.path.isdir(dirname):
raise ValueError("data directory '{}' does not exist".format(dirname))
raise ValueError(f"data directory '{dirname}' does not exist")

for each in get_test_files(dirname):
if os.path.isdir(each):
continue

fname = os.path.basename(each)
if fname.startswith('.'):
if fname.startswith("."):
continue

test_name, ext = os.path.splitext(fname)
data.setdefault(test_name, FileTestData(name=test_name, path=dirname))

# could setattr
attr = ext[1:]
if ext == '.expected':
if ext == ".expected":
with open(each) as fobj:
data[test_name].expected = json.load(fobj, object_hook=json_hook)
else:
Expand All @@ -115,10 +112,11 @@ def get_data(name):
return data


class RequestsData(object):
class RequestsData:
"""
class to use test data from requests
"""

def __init__(self, prefix, real_http=False):
self.prefix = prefix
adapter = requests_mock.Adapter()
Expand All @@ -127,7 +125,7 @@ def __init__(self, prefix, real_http=False):

def callback(self, request, context):
path = urllib.parse.urlparse(request.url).path
path = os.path.join(test_dir, 'data', self.prefix, path.lstrip('/'))
path = os.path.join(test_dir, "data", self.prefix, path.lstrip("/"))

files = get_test_files(path)

Expand All @@ -136,16 +134,16 @@ def callback(self, request, context):

if len(files) == 0:
# dir not found, check for file.input
fname = path + '.input'
fname = path + ".input"
if not os.path.exists(fname):
raise ValueError("failed to find data for {}".format(path))
raise ValueError(f"failed to find data for {path}")

else:
fname = files[0]

try:
# file extension is status code
context.status_code = int(os.path.splitext(fname)[1].lstrip('.'))
context.status_code = int(os.path.splitext(fname)[1].lstrip("."))

except ValueError:
context.status_code = 200
Expand Down
3 changes: 1 addition & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import os
import pytest
import pytest_filedata
Expand All @@ -11,6 +10,6 @@

def pytest_generate_tests(metafunc):
for fixture in metafunc.fixturenames:
if fixture.startswith('data_'):
if fixture.startswith("data_"):
data = pytest_filedata.get_data(fixture)
metafunc.parametrize(fixture, list(data.values()), ids=list(data.keys()))
10 changes: 6 additions & 4 deletions tests/test_filedata.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# -*- coding: utf-8 -*-

import pytest


def assert_json(data, parsed):
# dump in json format for easily adding expected
print("echo \\\n'{}'\\\n > {}/{}.expected".format(data.dumps(parsed), data.path, data.name))
print(
"echo \\\n'{}'\\\n > {}/{}.expected".format(
data.dumps(parsed), data.path, data.name
)
)
assert data.expected == parsed
assert data.name
assert data.path
Expand All @@ -16,6 +18,6 @@ def test_json_data(data_json):
assert_json(data_json, parsed)


#with pytest.raises(ValueError):
# with pytest.raises(ValueError):
# def test_nonexistant(data_nonexistant):
# pass
10 changes: 4 additions & 6 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-

import requests
import pytest
import pytest_filedata


def assert_test0(data):
res = requests.get('https://example.com/test0')
res = requests.get("https://example.com/test0")
assert res.status_code == 200
assert data.expected == res.json()

Expand All @@ -29,16 +27,16 @@ def test_input_extension(data_json):
@pytest_filedata.RequestsData("req")
def test_multiple_files():
with pytest.raises(NotImplementedError):
requests.get('https://example.com/multiple_files')
requests.get("https://example.com/multiple_files")


@pytest_filedata.RequestsData("req")
def test_missing_data():
with pytest.raises(ValueError):
requests.get('https://example.com/nonexistant')
requests.get("https://example.com/nonexistant")


@pytest_filedata.RequestsData("req")
def test_status_code():
res = requests.get('https://example.com/test404')
res = requests.get("https://example.com/test404")
res.status_code == 404

0 comments on commit 03438da

Please sign in to comment.