Skip to content

Commit

Permalink
Add a bunch of unit tests for missing statements
Browse files Browse the repository at this point in the history
  • Loading branch information
asgerius committed Feb 5, 2024
1 parent dcf5f23 commit f9500b5
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 7 deletions.
2 changes: 1 addition & 1 deletion pelutils/ds/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def histogram(
binning_fn: Callable[[_Array, int], _Array] = linear_binning,
bins: int = 25,
density: bool = True,
ignore_zeros: bool = False,
ignore_zeros: bool = False, # Be careful about this one, but it can be practical with log scales
):
""" Create bins for plotting a line histogram. Simplest usage is plt.plot(*histogram(data)) """
bins = np.array(binning_fn(data, bins+1))
Expand Down
1 change: 1 addition & 0 deletions pelutils/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,5 @@ def __str__(self) -> str:
))
if i in self._hlines:
strs.append(hline)

return os.linesep.join(strs)
12 changes: 11 additions & 1 deletion tests/ds/test_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from pelutils.ds.plots import linear_binning, log_binning, normal_binning, \
colours, base_colours, tab_colours, \
moving_avg, exp_moving_avg, double_moving_avg, \
Figure, get_dateticks
Figure, get_dateticks, histogram


def test_colours():
Expand Down Expand Up @@ -41,6 +41,16 @@ def test_get_dateticks():
assert labels[0] == start_time.strftime("%b %d")
assert labels[-1] == end_time.strftime("%b %d")

def test_histogram():
obs = [1, 2, 2, 1, 2]
x, y = histogram(obs)
assert isinstance(x, np.ndarray)
assert isinstance(y, np.ndarray)
assert (y >= 0).all()

x, y = histogram(obs, ignore_zeros=True)
assert (y > 0).all()

class TestMovingAverage:

def test_moving_avg(self):
Expand Down
16 changes: 15 additions & 1 deletion tests/ds/test_stats.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
import numpy as np
import pytest
from scipy.stats import norm

from pelutils.ds.stats import corr_ci
from pelutils.ds.stats import z, corr_ci


def test_z():
with pytest.raises(ValueError):
z(alpha=-0.01)
with pytest.raises(ValueError):
z(alpha=1.01)
t = z()
assert np.isclose(norm().cdf(t), 0.975)
assert np.isclose(norm().cdf(-t), 0.025)

t = z(two_sided=False)
assert np.isclose(norm().cdf(t), 0.95)
assert np.isclose(norm().cdf(-t), 0.05)

@pytest.mark.filterwarnings("ignore:divide by zero")
@pytest.mark.filterwarnings("ignore:invalid value")
def test_corr_ci():
Expand Down
16 changes: 13 additions & 3 deletions tests/logging/test_logging.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from itertools import chain, permutations, product
from string import ascii_lowercase
import multiprocessing as mp
import os
import re
from itertools import chain, permutations, product
from string import ascii_lowercase

import pelutils
import pytest
from pelutils import UnsupportedOS, OS

Expand Down Expand Up @@ -130,10 +131,19 @@ def test_log_commit(self, capfd: pytest.CaptureFixture):
pelutils git repository root or above. If not, this test will fail. """
log.log_repo()
stdout, _ = capfd.readouterr()
if ".git" in os.listdir("."):
if ".git" in os.listdir():
assert re.search(r"\b[0-9a-f]{40}\b", stdout)
assert "Unable" not in stdout
else:
assert re.search(r"\b[0-9a-f]{40}\b", stdout) is None
assert "Unable" in stdout

pelutils._has_git = False
log.log_repo()
stdout, _ = capfd.readouterr()
assert re.search(r"\b[0-9a-f]{40}\b", stdout) is None
assert "Unable" in stdout
pelutils._has_git = True

@pytest.mark.skipif(OS.is_windows, reason="Log collection is not supported on Windows")
def test_collect(self):
Expand Down
7 changes: 7 additions & 0 deletions tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ def test_table():

assert "+" not in str(t) # Check no header formatting

t = Table()
t.add_header(["a", "b", "c"])
t.add_row([1, 2, 3])
t.add_hline()
t.add_row([3, 4, 5])
assert str(t).count("+") == 4

def test_tex():
t = Table()
t.add_header(list(ascii_letters))
Expand Down
27 changes: 26 additions & 1 deletion tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
import os
import platform
from string import ascii_letters
from shutil import move

import numpy as np
import pytest
import torch

import pelutils
from pelutils import EnvVars, UnsupportedOS, reverse_line_iterator, except_keys,\
split_path, binary_search, raises, thousands_seperators, OS, array_ptr,\
get_timestamp, get_timestamp_for_files, HardwareInfo
get_timestamp, get_timestamp_for_files, HardwareInfo, get_repo
from pelutils.tests import UnitTestCollection

class TestInit(UnitTestCollection):
Expand Down Expand Up @@ -45,6 +47,7 @@ def test_thousands_seperator(self):
(1.234567e4, "12,345.67", "12.345,67"),
(1234567890, "1,234,567,890", "1.234.567.890"),
(0.03413, "0.03413", "0,03413"),
(-0.03413, "-0.03413", "-0,03413"),
)
for num, with_dot, with_comma in cases:
for neg in False, True:
Expand All @@ -55,6 +58,9 @@ def test_thousands_seperator(self):
assert with_dot == thousands_seperators(num, ".")
assert with_comma == thousands_seperators(num, ",")

with pytest.raises(ValueError):
thousands_seperators(1, "a")

def test_raises(self):
assert raises(IndexError, lambda x: x[0], [])
assert not raises(IndexError, lambda x: x[0], [1])
Expand Down Expand Up @@ -190,3 +196,22 @@ def test_hardware_info(self):
if HardwareInfo.gpus:
for gpu in HardwareInfo.gpus:
assert gpu in string

def test_get_repo(self):
if ".git" in os.listdir() and pelutils._has_git:
a, b = get_repo()
assert isinstance(a, str)
assert isinstance(b, str)

pelutils._has_git = False
a, b = get_repo()
assert a is None
assert b is None

pelutils._has_git = True
if ".git" in os.listdir():
move(".git", ".gittmp")
a, b = get_repo()
assert a is None
assert b is None
move(".gittmp", ".git")

0 comments on commit f9500b5

Please sign in to comment.