Skip to content

Commit

Permalink
Merge pull request #362 from pynapple-org/lint_tests
Browse files Browse the repository at this point in the history
linted tests
  • Loading branch information
gviejo authored Nov 6, 2024
2 parents 6132f60 + f4a4ab4 commit 93b9cd3
Show file tree
Hide file tree
Showing 33 changed files with 1,683 additions and 751 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ jobs:
black --check pynapple
isort --check pynapple --profile black
flake8 pynapple --max-complexity 10
black --check tests
isort --check tests --profile black
test:
needs: lint
runs-on: ${{ matrix.os }}
Expand Down
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
"""Unit test package for pynapple."""

from . import mock
8 changes: 4 additions & 4 deletions tests/mock.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Test configuration script."""
import numpy as np

import numpy as np


class MockArray:
Expand All @@ -19,8 +19,8 @@ def __init__(self, data):
A list of data elements that the MockArray will contain.
"""
self.data = np.asarray(data)
self.shape = self.data.shape # Simplified shape attribute
self.dtype = 'float64' # Simplified dtype; in real scenarios, this should be more dynamic
self.shape = self.data.shape # Simplified shape attribute
self.dtype = "float64" # Simplified dtype; in real scenarios, this should be more dynamic
self.ndim = self.data.ndim # Simplified ndim for a 1-dimensional array

def __getitem__(self, index):
Expand All @@ -46,4 +46,4 @@ def __len__(self):
"""
Returns the length of the mock array.
"""
return len(self.data)
return len(self.data)
29 changes: 16 additions & 13 deletions tests/test_abstract_tsd.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import pynapple as nap
import numpy as np
import pandas as pd
import pytest
from pynapple.core.time_series import _BaseTsd

import pynapple as nap
from pynapple.core.base_class import _Base
from pynapple.core.time_index import TsIndex
from pynapple.core.time_series import _BaseTsd


class MyClass(_BaseTsd):
Expand All @@ -21,6 +22,7 @@ def __str__(self):
def __repr__(self):
return "In repr"


class MyClass2(_Base):

def __getitem__(self, key):
Expand All @@ -35,6 +37,7 @@ def __str__(self):
def __repr__(self):
return "In repr"


def test_create_atsd():
a = MyClass(t=np.arange(10), d=np.arange(10))

Expand All @@ -43,12 +46,12 @@ def test_create_atsd():
assert hasattr(a, "values")
assert hasattr(a, "time_support")

assert np.isclose(a.rate, 10/9)
assert np.isclose(a.rate, 10 / 9)
assert isinstance(a.index, nap.TsIndex)
try:
assert isinstance(a.values, np.ndarray)
except:
assert nap.core.utils.is_array_like(a.values)
assert nap.core.utils.is_array_like(a.values)
assert isinstance(a.time_support, nap.IntervalSet)

assert hasattr(a, "t")
Expand Down Expand Up @@ -76,6 +79,7 @@ def test_create_atsd():
np.testing.assert_array_equal(a.values, b.values)
np.testing.assert_array_equal(a.index.values, b.index.values)


def test_create_ats():

a = MyClass2(t=np.arange(10))
Expand All @@ -85,14 +89,15 @@ def test_create_ats():
assert hasattr(a, "time_support")
assert hasattr(a, "shape")

assert np.isclose(a.rate, 10/9)
assert isinstance(a.index, nap.TsIndex)
assert np.isclose(a.rate, 10 / 9)
assert isinstance(a.index, nap.TsIndex)
assert isinstance(a.time_support, nap.IntervalSet)
assert a.shape == a.index.shape

assert hasattr(a, "t")
assert a[0] == 0


def test_create_ats_from_tsindex():

a = MyClass2(t=TsIndex(np.arange(10)))
Expand All @@ -102,12 +107,13 @@ def test_create_ats_from_tsindex():
assert hasattr(a, "time_support")
assert hasattr(a, "shape")

assert np.isclose(a.rate, 10/9)
assert isinstance(a.index, nap.TsIndex)
assert np.isclose(a.rate, 10 / 9)
assert isinstance(a.index, nap.TsIndex)
assert isinstance(a.time_support, nap.IntervalSet)
assert a.shape == a.index.shape

assert hasattr(a, "t")
assert hasattr(a, "t")


@pytest.mark.filterwarnings("ignore")
def test_create_ats_from_number():
Expand All @@ -118,7 +124,7 @@ def test_create_ats_from_number():
assert hasattr(a, "index")
assert hasattr(a, "time_support")
assert hasattr(a, "shape")


def test_methods():
a = MyClass(t=[], d=[])
Expand All @@ -143,6 +149,3 @@ def test_methods():
assert hasattr(a, "convolve")
assert hasattr(a, "smooth")
assert hasattr(a, "interpolate")



6 changes: 4 additions & 2 deletions tests/test_cnmfe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@

"""Tests of CNMFE loaders for `pynapple` package."""

import pynapple as nap
import warnings

import numpy as np
import pandas as pd
import pytest
import warnings

import pynapple as nap


@pytest.mark.filterwarnings("ignore")
Expand Down
151 changes: 99 additions & 52 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import warnings
from contextlib import nullcontext as does_not_raise

import numpy as np
import pytest

import pynapple as nap

import numpy as np

import warnings

class MockArray:
"""
Expand All @@ -25,8 +24,8 @@ def __init__(self, data):
A list of data elements that the MockArray will contain.
"""
self.data = np.asarray(data)
self.shape = self.data.shape # Simplified shape attribute
self.dtype = 'float64' # Simplified dtype; in real scenarios, this should be more dynamic
self.shape = self.data.shape # Simplified shape attribute
self.dtype = "float64" # Simplified dtype; in real scenarios, this should be more dynamic
self.ndim = self.data.ndim # Simplified ndim for a 1-dimensional array

def __getitem__(self, index):
Expand Down Expand Up @@ -56,6 +55,7 @@ def __len__(self):
"""
return len(self.data)


##################################
# Test for backend
##################################
Expand All @@ -65,36 +65,45 @@ def test_change_backend():
assert nap.core.utils.get_backend() == "numba"
assert nap.nap_config.backend == "numba"

with pytest.raises(AssertionError, match="Options for backend are 'jax' or 'numba'"):
with pytest.raises(
AssertionError, match="Options for backend are 'jax' or 'numba'"
):
nap.nap_config.set_backend("blabla")

# For local tests.
# Should not be installed for github actions
# Should not be installed for github actions
# try:
# import pynajax

# nap.nap_config.set_backend("jax")
# assert nap.core.utils.get_backend() == "jax"
# assert nap.nap_config.backend == "jax"

# except ModuleNotFoundError:
# with warnings.catch_warnings(record=True) as w:
# nap.nap_config.set_backend("jax")
# except ModuleNotFoundError:
# with warnings.catch_warnings(record=True) as w:
# nap.nap_config.set_backend("jax")

# assert str(w[0].message) == 'Package pynajax is not found. Falling back to numba backend. To use the jax backend for pynapple, please install pynajax'
# assert nap.core.utils.get_backend() == "numba"
# assert nap.nap_config.backend == "numba"


# assert str(w[0].message) == 'Package pynajax is not found. Falling back to numba backend. To use the jax backend for pynapple, please install pynajax'
# assert nap.core.utils.get_backend() == "numba"
# assert nap.nap_config.backend == "numba"

##################################
# Tests for warnings
##################################
@pytest.mark.parametrize("param, expectation",
[
(True, does_not_raise()),
(False, does_not_raise()),
(1, pytest.raises(ValueError,
match="suppress_conversion_warnings must be a boolean value"))
])
@pytest.mark.parametrize(
"param, expectation",
[
(True, does_not_raise()),
(False, does_not_raise()),
(
1,
pytest.raises(
ValueError, match="suppress_conversion_warnings must be a boolean value"
),
),
],
)
def test_config_setter_input_validity(param, expectation):
"""Test setting suppress_conversion_warnings with various inputs to validate type checking."""
with expectation:
Expand All @@ -114,22 +123,43 @@ def test_config_restore_default():
assert not nap.nap_config.suppress_conversion_warnings


@pytest.mark.parametrize("cls, t, d, conf, expectation",
[
(nap.Ts, [0, 1], None, True, does_not_raise()),
(nap.Ts, [0, 1], None, False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array.")),
(nap.Tsd, [0, 1], [0, 1], True, does_not_raise()),
(nap.Tsd, [0, 1], [0, 1], False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array.")),
(nap.TsdFrame, [0, 1], [[0], [1]], True, does_not_raise()),
(nap.TsdFrame, [0, 1], [[0], [1]], False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array.")),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], True, does_not_raise()),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array.")),
])
@pytest.mark.parametrize(
"cls, t, d, conf, expectation",
[
(nap.Ts, [0, 1], None, True, does_not_raise()),
(
nap.Ts,
[0, 1],
None,
False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array."),
),
(nap.Tsd, [0, 1], [0, 1], True, does_not_raise()),
(
nap.Tsd,
[0, 1],
[0, 1],
False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array."),
),
(nap.TsdFrame, [0, 1], [[0], [1]], True, does_not_raise()),
(
nap.TsdFrame,
[0, 1],
[[0], [1]],
False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array."),
),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], True, does_not_raise()),
(
nap.TsdTensor,
[0, 1],
[[[0]], [[1]]],
False,
pytest.warns(UserWarning, match=f"Converting 't' to numpy.array."),
),
],
)
def test_config_supress_warning_t(cls, t, d, conf, expectation):
"""Test if the restore_defaults method correctly resets suppress_conversion_warnings to its default."""
nap.nap_config.suppress_conversion_warnings = conf
Expand All @@ -142,19 +172,36 @@ def test_config_supress_warning_t(cls, t, d, conf, expectation):
finally:
nap.nap_config.restore_defaults()

@pytest.mark.parametrize("cls, t, d, conf, expectation",
[
(nap.Tsd, [0, 1], [0, 1], True, does_not_raise()),
(nap.Tsd, [0, 1], [0, 1], False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array.")),
(nap.TsdFrame, [0, 1], [[0], [1]], True, does_not_raise()),
(nap.TsdFrame, [0, 1], [[0], [1]], False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array.")),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], True, does_not_raise()),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array.")),
])

@pytest.mark.parametrize(
"cls, t, d, conf, expectation",
[
(nap.Tsd, [0, 1], [0, 1], True, does_not_raise()),
(
nap.Tsd,
[0, 1],
[0, 1],
False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array."),
),
(nap.TsdFrame, [0, 1], [[0], [1]], True, does_not_raise()),
(
nap.TsdFrame,
[0, 1],
[[0], [1]],
False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array."),
),
(nap.TsdTensor, [0, 1], [[[0]], [[1]]], True, does_not_raise()),
(
nap.TsdTensor,
[0, 1],
[[[0]], [[1]]],
False,
pytest.warns(UserWarning, match=f"Converting 'd' to numpy.array."),
),
],
)
def test_config_supress_warning_d(cls, t, d, conf, expectation):
"""Test if the restore_defaults method correctly resets suppress_conversion_warnings to its default."""
nap.nap_config.suppress_conversion_warnings = conf
Expand All @@ -166,4 +213,4 @@ def test_config_supress_warning_d(cls, t, d, conf, expectation):


def test_get_time_index_precision():
assert nap.nap_config.time_index_precision == 9
assert nap.nap_config.time_index_precision == 9
7 changes: 5 additions & 2 deletions tests/test_correlograms.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Tests of correlograms for `pynapple` package."""

import pynapple as nap
from itertools import combinations

import numpy as np
import pandas as pd
import pytest
from itertools import combinations

import pynapple as nap


def test_cross_correlogram():
t1 = np.array([0])
Expand Down
Loading

0 comments on commit 93b9cd3

Please sign in to comment.