A pytest approxable dict mixin for data class
Project description
Pytest Approxable Mixin
Example
from pytest_approxable import Approxable
from dataclasses import dataclass
from pytest import approx
@dataclass
class MetalProperties(Approxable):
name: str
heat_capacity: float
conductivity: float
def test_metal_equal():
mp1 = MetalProperties(name='metal1', heat_capacity=0.5, conductivity=1.)
mp2 = MetalProperties(name='metal2', heat_capacity=0.499999999, conductivity=0.9999999998)
assert approx(mp1.approxable_dict, abs=0.1) == mp2.approxable_dict
Problem
When testing codes, we usually approximate floating numbers to avoid decimal points error. To do so, we use pytest.approx
as follow
from pytest import approx
def test_approx():
a = 1.0000000000000001
b = 1.
assert approx(a, abs=0.1) == b # this will pass
assert a == b # this will fail
Moreover, we can also use this with the dictionary derived from a dataclass. For example,
from dataclasses import dataclass, asdict
from pytest import approx
@dataclass
class MetalProperties:
heat_capacity: float
conductivity: float
def test_metal_equal():
mp1 = MetalProperties(heat_capacity=0.5, conductivity=1.)
mp2 = MetalProperties(heat_capacity=0.499999999, conductivity=0.9999999998)
assert approx(asdict(mp1), abs=0.1) == asdict(mp2)
Now the problem arises when we have non-number fields in the class
@dataclass
class MetalProperties:
name: str
heat_capacity: float
conductivity: float
def test_metal_equal():
mp1 = MetalProperties(name='metal1', heat_capacity=0.5, conductivity=1.)
mp2 = MetalProperties(name='metal2', heat_capacity=0.499999999, conductivity=0.9999999998)
assert approx(asdict(mp1), abs=0.1) == asdict(mp2)
Above code will fails since attribute name
can't be approximated
##Progress
- tests
- supports nested object
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for hackinteach-pytest-approxable-0.0.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | f3c06bffe717ae1a4d0d6398c75019579316df98a9b3fb8c85debc9287bae34c |
|
MD5 | fa748f07b818932b205328e351b141bf |
|
BLAKE2b-256 | fc1d8545fbddf01b05ab7f92fa717d01e6e9210d1a0f2e4fc9df38fd82590e36 |
Close
Hashes for hackinteach_pytest_approxable-0.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d4d65a44ddf0da3253fe6a8617c9310adc758054bc48c33625a86c298430b27f |
|
MD5 | 029428816c4c283c0a74a245bed61b35 |
|
BLAKE2b-256 | 7c9e8a80a5c9184313dc39c187ef083473426dc076920a245537c3ad73148092 |