marbles.mixins
This module provides custom |
|
Built-in assertions about betweenness. |
|
Built-in assertions about monotonicity. |
|
Built-in assertions about uniqueness. |
|
Built-in assertions for files. |
|
Built-in assertions for categorical data. |
|
Built-in assertions for |
This module provides custom unittest-style assertions. For
the most part, marbles.mixins assertions trivially wrap
unittest assertions. For example, a call to
CategoricalMixins.assertCategoricalLevelIn() will simply pass the
provided arguments to assertIn().
Custom assertions are provided via mixins so that they can use other assertions as building blocks. Using mixins, instead of straight inheritance, means that users can compose multiple mixins to create a test case with all the assertions that they need.
Warning
marbles.mixins can be mixed into a
unittest.TestCase, a marbles.core.TestCase,
a marbles.core.AnnotatedTestCase, or any other class that
implements a unittest.TestCase interface. To enforce
this, mixins define abstract methods. This means that,
when mixing them into your test case, they must come after the
class(es) that implement those methods instead of appearing first
in the inheritance list like normal mixins.
Example:
import unittest
from marbles.core import marbles
from marbles.mixins import mixins
class MyTestCase(unittest.TestCase, mixins.BetweenMixins):
def test_me(self):
self.assertBetween(5, lower=0, upper=10)
class MyMarblesTestCase(marbles.TestCase, mixins.BetweenMixins):
def test_me(self):
self.assertBetween(5, lower=0, upper=10)
- class marbles.mixins.BetweenMixins[source]
Built-in assertions about betweenness.
- assertBetween(obj, lower, upper, strict=True, msg=None)[source]
Fail if
objis not betweenlowerandupper.If
strict=True(default), fail unlesslower < obj < upper. Ifstrict=False, fail unlesslower <= obj <= upper.This is equivalent to
self.assertTrue(lower < obj < upper)orself.assertTrue(lower <= obj <= upper), but with a nicer default message.- Parameters:
obj –
lower –
upper –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- assertNotBetween(obj, lower, upper, strict=True, msg=None)[source]
Fail if
objis betweenlowerandupper.If
strict=True(default), fail iflower <= obj <= upper. Ifstrict=False, fail iflower < obj < upper.This is equivalent to
self.assertFalse(lower < obj < upper)orself.assertFalse(lower <= obj <= upper), but with a nicer default message.- Raises:
ValueError – If
lowerequalsupperandstrict=Trueis specified.- Parameters:
obj –
lower –
upper –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- class marbles.mixins.CategoricalMixins[source]
Built-in assertions for categorical data.
This mixin includes some common categorical variables (e.g., weekdays, months, U.S. states, etc.) that test authors can use test resources against. For instance, if a dataset is supposed to contain data for all states in the U.S., test authors can test the state column in their dataset against the US_STATES attribute.
import unittest from marbles.mixins import mixins class MyTestCase(unittest.TestCase, mixins.CategoricalMixins): def test_that_all_states_are_present(self): df = ... self.assertCategoricalLevelsEqual(df['STATE'], self.US_STATES)
These categorical variables are provided as a convenience; test authors can and should manipulate these variables, or create their own, as needed. The idea is, for expectations that may apply across datasets, to ensure that the same expectation is being tested in the same way across different datasets.
- assertCategoricalLevelsEqual(levels1, levels2, msg=None)[source]
Fail if
levels1andlevels2do not have the same domain.- Parameters:
levels1 (iterable) –
levels2 (iterable) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If either
levels1orlevels2is not iterable.
- assertCategoricalLevelsNotEqual(levels1, levels2, msg=None)[source]
Fail if
levels1andlevels2have the same domain.- Parameters:
levels1 (iterable) –
levels2 (iterable) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If either
levels1orlevels2is not iterable.
- assertCategoricalLevelIn(level, levels, msg=None)[source]
Fail if
levelis not inlevels.This is equivalent to
self.assertIn(level, levels).- Parameters:
level –
levels (iterable) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
levelsis not iterable.
- assertCategoricalLevelNotIn(level, levels, msg=None)[source]
Fail if
levelis inlevels.This is equivalent to
self.assertNotIn(level, levels).- Parameters:
level –
levels (iterable) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
levelsis not iterable.
- class marbles.mixins.DateTimeMixins[source]
Built-in assertions for
dates,datetimes, andtimes.- assertDateTimesBefore(sequence, target, strict=True, msg=None)[source]
Fail if any elements in
sequenceare not beforetarget.If
targetis iterable, it must have the same length assequenceIf
strict=True, fail unless all elements insequenceare strictly less thantarget. Ifstrict=False, fail unless all elements insequenceare less than or equal totarget.- Parameters:
sequence (iterable) –
target (datetime, date, iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.ValueError – If
targetis iterable but does not have the same length assequence.TypeError – If
targetis not a datetime or date object and is not iterable.
- assertDateTimesAfter(sequence, target, strict=True, msg=None)[source]
Fail if any elements in
sequenceare not aftertarget.If
targetis iterable, it must have the same length assequenceIf
strict=True, fail unless all elements insequenceare strictly greater thantarget. Ifstrict=False, fail unless all elements insequenceare greater than or equal totarget.- Parameters:
sequence (iterable) –
target (datetime, date, iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.ValueError – If
targetis iterable but does not have the same length assequence.TypeError – If
targetis not a datetime or date object and is not iterable.
- assertDateTimesPast(sequence, strict=True, msg=None)[source]
Fail if any elements in
sequenceare not in the past.If the max element is a datetime, “past” is defined as anything prior to
datetime.now(); if the max element is a date, “past” is defined as anything prior todate.today().If
strict=True, fail unless all elements insequenceare strictly less thandate.today()(ordatetime.now()). Ifstrict=False, fail unless all elements insequenceare less than or equal todate.today()(ordatetime.now()).
- assertDateTimesFuture(sequence, strict=True, msg=None)[source]
Fail if any elements in
sequenceare not in the future.If the min element is a datetime, “future” is defined as anything after
datetime.now(); if the min element is a date, “future” is defined as anything afterdate.today().If
strict=True, fail unless all elements insequenceare strictly greater thandate.today()(ordatetime.now()). Ifstrict=False, fail all elements insequenceare greater than or equal todate.today()(ordatetime.now()).
- assertDateTimesFrequencyEqual(sequence, frequency, msg=None)[source]
Fail if any elements in
sequencearen’t separated by the expectedfequency.- Parameters:
sequence (iterable) –
frequency (timedelta) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- assertDateTimesLagEqual(sequence, lag, msg=None)[source]
Fail unless max element in
sequenceis separated from the present bylagas determined by the ‘==’ operator.If the max element is a datetime, “present” is defined as
datetime.now(); if the max element is a date, “present” is defined asdate.today().This is equivalent to
self.assertEqual(present - max(sequence), lag).- Parameters:
sequence (iterable) –
lag (timedelta) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- assertDateTimesLagLess(sequence, lag, msg=None)[source]
Fail if max element in
sequenceis separated from the present bylagor more as determined by the ‘<’ operator.If the max element is a datetime, “present” is defined as
datetime.now(); if the max element is a date, “present” is defined asdate.today().This is equivalent to
self.assertLess(present - max(sequence), lag).- Parameters:
sequence (iterable) –
lag (timedelta) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- assertDateTimesLagLessEqual(sequence, lag, msg=None)[source]
Fail if max element in
sequenceis separated from the present by more thanlagas determined by the ‘<=’ operator.If the max element is a datetime, “present” is defined as
datetime.now(); if the max element is a date, “present” is defined asdate.today().This is equivalent to
self.assertLessEqual(present - max(sequence), lag).- Parameters:
sequence (iterable) –
lag (timedelta) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- assertTimeZoneIsNone(dt, msg=None)[source]
Fail if
dthas a non-nulltzinfoattribute.- Parameters:
dt (datetime) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
dtis not a datetime object.
- assertTimeZoneIsNotNone(dt, msg=None)[source]
Fail unless
dthas a non-nulltzinfoattribute.- Parameters:
dt (datetime) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
dtis not a datetime object.
- assertTimeZoneEqual(dt, tz, msg=None)[source]
Fail unless
dt’stzinfoattribute equalstzas determined by the ‘==’ operator.- Parameters:
dt (datetime) –
tz (timezone) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- assertTimeZoneNotEqual(dt, tz, msg=None)[source]
Fail if
dt’stzinfoattribute equalstzas determined by the ‘!=’ operator.- Parameters:
dt (datetime) –
tz (timezone) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
- class marbles.mixins.FileMixins[source]
Built-in assertions for files.
With the exception of
assertFileExists()andassertFileNotExists(), all custom file assertions take afilenameargument which can accept a file name as astrorbytesobject, or a file-like object. Accepting a file-like object is useful for testing files that are not present locally, e.g., files in HDFS.import unittest import hdfs3 from marbles.mixins import mixins class MyFileTest(unittest.TestCase, mixins.FileMixins): def test_file_encoding(self): fname = 'myfile.csv' # You can pass fname directly to the assertion (if the # file exists locally) self.assertFileEncodingEqual(fname, 'utf-8') # Or open the file and pass a file descriptor to the # assertion with open(fname) as f: self.assertFileEncodingEqual(f, 'utf-8') def test_hdfs_file_encoding(self): hdfspath = '/path/to/myfile.csv' client = hdfs3.HDFileSystem(host='host', port='port') with client.open(hdfspath) as f: self.assertFileEncodingEqual(f, 'utf-8')
Note that not all file-like objects implement the expected interface. These custom file assertions expect the following methods and attributes:
read()write()seek()tell()nameencoding
- assertFileExists(filename, msg=None)[source]
Fail if
filenamedoes not exist as determined byos.path.isfile(filename).- Parameters:
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- assertFileNotExists(filename, msg=None)[source]
Fail if
filenameexists as determined by~os.path.isfile(filename).- Parameters:
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- assertFileNameEqual(filename, name, msg=None)[source]
Fail if
filenamedoes not have the givennameas determined by the==operator.
- assertFileNameNotEqual(filename, name, msg=None)[source]
Fail if
filenamehas the givennameas determined by the!=operator.
- assertFileNameRegex(filename, expected_regex, msg=None)[source]
Fail unless
filenamematchesexpected_regex.
- assertFileNameNotRegex(filename, expected_regex, msg=None)[source]
Fail if
filenamematchesexpected_regex.
- assertFileTypeEqual(filename, extension, msg=None)[source]
Fail if
filenamedoes not have the givenextensionas determined by the==operator.
- assertFileTypeNotEqual(filename, extension, msg=None)[source]
Fail if
filenamehas the givenextensionas determined by the!=operator.
- assertFileEncodingEqual(filename, encoding, msg=None)[source]
Fail if
filenameis not encoded with the givenencodingas determined by the ‘==’ operator.
- assertFileEncodingNotEqual(filename, encoding, msg=None)[source]
Fail if
filenameis encoded with the givenencodingas determined by the ‘!=’ operator.
- assertFileSizeEqual(filename, size, msg=None)[source]
Fail if
filenamedoes not have the givensizeas determined by the ‘==’ operator.
- assertFileSizeNotEqual(filename, size, msg=None)[source]
Fail if
filenamehas the givensizeas determined by the ‘!=’ operator.
- assertFileSizeAlmostEqual(filename, size, places=None, msg=None, delta=None)[source]
Fail if
filenamedoes not have the givensizeas determined by their difference rounded to the given number of decimalplaces(default 7) and comparing to zero, or if their difference is greater than a givendelta.
- assertFileSizeNotAlmostEqual(filename, size, places=None, msg=None, delta=None)[source]
Fail unless
filenamedoes not have the givensizeas determined by their difference rounded to the given number ofdecimalplaces(default 7) and comparing to zero, or if their difference is greater than a givendelta.
- assertFileSizeGreater(filename, size, msg=None)[source]
Fail if
filename’s size is not greater thansizeas determined by the ‘>’ operator.
- assertFileSizeGreaterEqual(filename, size, msg=None)[source]
Fail if
filename’s size is not greater than or equal tosizeas determined by the ‘>=’ operator.
- assertFileSizeLess(filename, size, msg=None)[source]
Fail if
filename’s size is not less thansizeas determined by the ‘<’ operator.
- class marbles.mixins.MonotonicMixins[source]
Built-in assertions about monotonicity.
- assertMonotonicIncreasing(sequence, strict=True, msg=None)[source]
Fail if
sequenceis not monotonically increasing.If
strict=True(default), fail unless each element insequenceis less than the following element as determined by the<operator. Ifstrict=False, fail unless each element insequenceis less than or equal to the following element as determined by the<=operator.assert all((i < j) for i, j in zip(sequence, sequence[1:])) assert all((i <= j) for i, j in zip(sequence, sequence[1:]))
- Parameters:
sequence (iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.
- assertNotMonotonicIncreasing(sequence, strict=True, msg=None)[source]
Fail if
sequenceis monotonically increasing.If
strict=True(default), fail if each element insequenceis less than the following element as determined by the<operator. Ifstrict=False, fail if each element insequenceis less than or equal to the following element as determined by the<=operator.assert not all((i < j) for i, j in zip(sequence, sequence[1:])) assert not all((i <= j) for i, j in zip(sequence, sequence[1:]))
- Parameters:
sequence (iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.
- assertMonotonicDecreasing(sequence, strict=True, msg=None)[source]
Fail if
sequenceis not monotonically decreasing.If
strict=True(default), fail unless each element insequenceis greater than the following element as determined by the>operator. Ifstrict=False, fail unless each element insequenceis greater than or equal to the following element as determined by the>=operator.assert all((i > j) for i, j in zip(sequence, sequence[1:])) assert all((i >= j) for i, j in zip(sequence, sequence[1:]))
- Parameters:
sequence (iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.
- assertNotMonotonicDecreasing(sequence, strict=True, msg=None)[source]
Fail if
sequenceis monotonically decreasing.If
strict=True(default), fail if each element insequenceis greater than the following element as determined by the>operator. Ifstrict=False, fail if each element insequenceis greater than or equal to the following element as determined by the>=operator.assert not all((i > j) for i, j in zip(sequence, sequence[1:])) assert not all((i >= j) for i, j in zip(sequence, sequence[1:]))
- Parameters:
sequence (iterable) –
strict (bool) –
msg (str) – If not provided, the
marbles.mixinsorunitteststandard message will be used.
- Raises:
TypeError – If
sequenceis not iterable.
- class marbles.mixins.UniqueMixins[source]
Built-in assertions about uniqueness.
These assertions can handle containers that contain unhashable elements.