mapFolding 0.2.1__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tests/conftest.py CHANGED
@@ -3,31 +3,34 @@ Other test modules must not import directly from the package being tested."""
3
3
 
4
4
  # TODO learn how to run tests and coverage analysis without `env = ["NUMBA_DISABLE_JIT=1"]`
5
5
 
6
- from typing import Any, Callable, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union
6
+ from typing import Any, Callable, Dict, Generator, List, Optional, Sequence, Set, Tuple, Type, Union
7
7
  import pathlib
8
8
  import pytest
9
9
  import random
10
+ import shutil
10
11
  import unittest.mock
11
-
12
- from mapFolding import clearOEIScache
13
- from mapFolding import countFolds, pathJobDEFAULT
14
- from mapFolding import getLeavesTotal, parseDimensions, validateListDimensions
15
- from mapFolding.importPackages import makeTestSuiteConcurrencyLimit, defineConcurrencyLimit
16
- from mapFolding.importPackages import makeTestSuiteIntInnit, intInnit
17
- from mapFolding.importPackages import makeTestSuiteOopsieKwargsie, oopsieKwargsie
12
+ import uuid
13
+ from Z0Z_tools.pytest_parseParameters import makeTestSuiteConcurrencyLimit
14
+ from Z0Z_tools.pytest_parseParameters import makeTestSuiteIntInnit
15
+ from Z0Z_tools.pytest_parseParameters import makeTestSuiteOopsieKwargsie
16
+ from mapFolding import countFolds, pathJobDEFAULT, indexMy, indexThe, indexTrack
17
+ from mapFolding import defineConcurrencyLimit, intInnit, oopsieKwargsie, outfitCountFolds
18
+ from mapFolding import oeisIDfor_n, getOEISids, clearOEIScache, getFilenameFoldsTotal
19
+ from mapFolding.beDRY import getLeavesTotal, parseDimensions, validateListDimensions
20
+ from mapFolding.beDRY import getTaskDivisions, makeConnectionGraph, setCPUlimit
21
+ from mapFolding.beDRY import makeDataContainer
18
22
  from mapFolding.oeis import OEIS_for_n
19
- from mapFolding.oeis import _formatFilenameCache
23
+ from mapFolding.oeis import _getFilenameOEISbFile
20
24
  from mapFolding.oeis import _getOEISidValues
21
25
  from mapFolding.oeis import _parseBFileOEIS
22
26
  from mapFolding.oeis import _validateOEISid
23
- from mapFolding.oeis import getOEISids
24
- from mapFolding.oeis import oeisIDfor_n
25
27
  from mapFolding.oeis import oeisIDsImplemented
26
28
  from mapFolding.oeis import settingsOEIS
29
+ from mapFolding import *
27
30
 
28
31
  __all__ = [
29
32
  'OEIS_for_n',
30
- '_formatFilenameCache',
33
+ '_getFilenameOEISbFile',
31
34
  '_getOEISidValues',
32
35
  '_parseBFileOEIS',
33
36
  '_validateOEISid',
@@ -35,16 +38,23 @@ __all__ = [
35
38
  'countFolds',
36
39
  'defineConcurrencyLimit',
37
40
  'expectSystemExit',
41
+ 'getFilenameFoldsTotal',
38
42
  'getLeavesTotal',
39
43
  'getOEISids',
44
+ 'getTaskDivisions',
45
+ 'indexThe',
40
46
  'intInnit',
47
+ 'makeConnectionGraph',
48
+ 'makeDataContainer',
41
49
  'makeTestSuiteConcurrencyLimit',
42
50
  'makeTestSuiteIntInnit',
43
51
  'makeTestSuiteOopsieKwargsie',
44
52
  'oeisIDfor_n',
45
53
  'oeisIDsImplemented',
46
54
  'oopsieKwargsie',
55
+ 'outfitCountFolds',
47
56
  'parseDimensions',
57
+ 'setCPUlimit',
48
58
  'settingsOEIS',
49
59
  'standardCacheTest',
50
60
  'standardComparison',
@@ -91,6 +101,75 @@ def makeDictionaryFoldsTotalKnown() -> Dict[Tuple[int,...], int]:
91
101
 
92
102
  return dictionaryMapDimensionsToFoldsTotalKnown
93
103
 
104
+ """
105
+ Section: temporary paths and pathFilenames"""
106
+
107
+ # SSOT for test data paths
108
+ pathDataSamples = pathlib.Path("tests/dataSamples")
109
+ pathTempRoot = pathDataSamples / "tmp"
110
+
111
+ # The registrar maintains the register of temp files
112
+ registerOfTempFiles: Set[pathlib.Path] = set()
113
+
114
+ def addTempFileToRegister(path: pathlib.Path) -> None:
115
+ """The registrar adds a temp file to the register."""
116
+ registerOfTempFiles.add(path)
117
+
118
+ def cleanupTempFileRegister() -> None:
119
+ """The registrar cleans up temp files in the register."""
120
+ for pathTemp in sorted(registerOfTempFiles, reverse=True):
121
+ try:
122
+ if pathTemp.is_file():
123
+ pathTemp.unlink(missing_ok=True)
124
+ elif pathTemp.is_dir():
125
+ shutil.rmtree(pathTemp, ignore_errors=True)
126
+ except Exception as ERRORmessage:
127
+ print(f"Warning: Failed to clean up {pathTemp}: {ERRORmessage}")
128
+ registerOfTempFiles.clear()
129
+
130
+ @pytest.fixture(scope="session", autouse=True)
131
+ def setupTeardownTestData() -> Generator[None, None, None]:
132
+ """Auto-fixture to setup test data directories and cleanup after."""
133
+ pathDataSamples.mkdir(exist_ok=True)
134
+ pathTempRoot.mkdir(exist_ok=True)
135
+ yield
136
+ cleanupTempFileRegister()
137
+
138
+ @pytest.fixture
139
+ def pathTempTesting(request: pytest.FixtureRequest) -> pathlib.Path:
140
+ """Create a unique temp directory for each test function."""
141
+ # Sanitize test name for filesystem compatibility
142
+ sanitizedName = request.node.name.replace('[', '_').replace(']', '_').replace('/', '_')
143
+ uniqueDirectory = f"{sanitizedName}_{uuid.uuid4()}"
144
+ pathTemp = pathTempRoot / uniqueDirectory
145
+ pathTemp.mkdir(parents=True, exist_ok=True)
146
+
147
+ addTempFileToRegister(pathTemp)
148
+ return pathTemp
149
+
150
+ @pytest.fixture
151
+ def pathCacheTesting(pathTempTesting: pathlib.Path) -> Generator[pathlib.Path, Any, None]:
152
+ """Temporarily replace the OEIS cache directory with a test directory."""
153
+ from mapFolding import oeis as there_must_be_a_better_way
154
+ pathCacheOriginal = there_must_be_a_better_way._pathCache
155
+ there_must_be_a_better_way._pathCache = pathTempTesting
156
+ yield pathTempTesting
157
+ there_must_be_a_better_way._pathCache = pathCacheOriginal
158
+
159
+ @pytest.fixture
160
+ def pathFilenameBenchmarksTesting(pathTempTesting: pathlib.Path) -> Generator[pathlib.Path, Any, None]:
161
+ """Temporarily replace the benchmarks directory with a test directory."""
162
+ from mapFolding.benchmarks import benchmarking
163
+ pathFilenameOriginal = benchmarking.pathFilenameRecordedBenchmarks
164
+ pathFilenameTest = pathTempTesting / "benchmarks.npy"
165
+ benchmarking.pathFilenameRecordedBenchmarks = pathFilenameTest
166
+ yield pathFilenameTest
167
+ benchmarking.pathFilenameRecordedBenchmarks = pathFilenameOriginal
168
+
169
+ @pytest.fixture
170
+ def pathFilenameFoldsTotalTesting(pathTempTesting: pathlib.Path) -> pathlib.Path:
171
+ return pathTempTesting.joinpath("foldsTotalTest.txt")
172
+
94
173
  """
95
174
  Section: Fixtures"""
96
175
 
@@ -151,27 +230,30 @@ def oeisID_1random() -> str:
151
230
  return random.choice(oeisIDsImplemented)
152
231
 
153
232
  @pytest.fixture
154
- def pathCacheTesting(tmp_path: pathlib.Path) -> Generator[pathlib.Path, Any, None]:
155
- """Temporarily replace the OEIS cache directory with a test directory."""
156
- from mapFolding import oeis as there_must_be_a_better_way
157
- pathCacheOriginal = there_must_be_a_better_way._pathCache
158
- there_must_be_a_better_way._pathCache = tmp_path
159
- yield tmp_path
160
- there_must_be_a_better_way._pathCache = pathCacheOriginal
233
+ def mockFoldingFunction():
234
+ """Creates a mock function that simulates _countFolds behavior."""
235
+ def make_mock(foldsValue: int, listDimensions: List[int]):
236
+ arraySize = getLeavesTotal(listDimensions)
237
+ # The array needs to sum to our target value
238
+ mock_array = makeDataContainer(arraySize)
239
+ mock_array[arraySize - 1] = foldsValue # Put entire value in last position
161
240
 
162
- @pytest.fixture
163
- def pathBenchmarksTesting(tmp_path: pathlib.Path) -> Generator[pathlib.Path, Any, None]:
164
- """Temporarily replace the benchmarks directory with a test directory."""
165
- from mapFolding.benchmarks import benchmarking
166
- pathOriginal = benchmarking.pathFilenameRecordedBenchmarks
167
- pathTest = tmp_path / "benchmarks.npy"
168
- benchmarking.pathFilenameRecordedBenchmarks = pathTest
169
- yield pathTest
170
- benchmarking.pathFilenameRecordedBenchmarks = pathOriginal
241
+ def mock_countfolds(**keywordArguments):
242
+ keywordArguments['foldsSubTotals'][:] = mock_array
243
+ return None
244
+
245
+ return mock_countfolds
246
+ return make_mock
171
247
 
172
248
  """
173
249
  Section: Standardized test structures"""
174
250
 
251
+ def formatTestMessage(expected: Any, actual: Any, functionName: str, *arguments: Any) -> str:
252
+ """Format assertion message for any test comparison."""
253
+ return (f"\nTesting: `{functionName}({', '.join(str(parameter) for parameter in arguments)})`\n"
254
+ f"Expected: {expected}\n"
255
+ f"Got: {actual}")
256
+
175
257
  def standardComparison(expected: Any, functionTarget: Callable, *arguments: Any) -> None:
176
258
  """Template for tests expecting an error."""
177
259
  if type(expected) == Type[Exception]:
@@ -217,12 +299,6 @@ def expectSystemExit(expected: Union[str, int, Sequence[int]], functionTarget: C
217
299
  assert exitCode == expected, \
218
300
  f"Expected exit code {expected} but got {exitCode}"
219
301
 
220
- def formatTestMessage(expected: Any, actual: Any, functionName: str, *arguments: Any) -> str:
221
- """Format assertion message for any test comparison."""
222
- return (f"\nTesting: `{functionName}({', '.join(str(parameter) for parameter in arguments)})`\n"
223
- f"Expected: {expected}\n"
224
- f"Got: {actual}")
225
-
226
302
  def standardCacheTest(
227
303
  expected: Any,
228
304
  setupCacheFile: Optional[Callable[[pathlib.Path, str], None]],
@@ -237,7 +313,7 @@ def standardCacheTest(
237
313
  oeisID: OEIS ID to test
238
314
  pathCache: Temporary cache directory path
239
315
  """
240
- pathFilenameCache = pathCache / _formatFilenameCache.format(oeisID=oeisID)
316
+ pathFilenameCache = pathCache / _getFilenameOEISbFile(oeisID)
241
317
 
242
318
  # Setup cache file if provided
243
319
  if setupCacheFile:
@@ -0,0 +1 @@
1
+ from mapFolding.theSSOT import *
tests/test_oeis.py CHANGED
@@ -1,6 +1,7 @@
1
- from .conftest import *
1
+ from tests.conftest import *
2
2
  from contextlib import redirect_stdout
3
3
  from datetime import datetime, timedelta
4
+ from typing import Optional, Tuple, Union
4
5
  import io
5
6
  import os
6
7
  import pathlib
@@ -62,29 +63,27 @@ def test_clearOEIScache(mock_unlink: unittest.mock.MagicMock, mock_exists: unitt
62
63
  mock_exists.assert_called_once()
63
64
  mock_unlink.assert_not_called()
64
65
 
65
- def testCacheMiss(pathCacheTesting: pathlib.Path, oeisID_1random: str):
66
- """Test cache miss scenario - cache file doesn't exist."""
67
- # No setup function needed - we want to test missing cache
68
- standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], None, oeisID_1random, pathCacheTesting)
66
+ @pytest.mark.parametrize("scenarioCache", ["miss", "expired", "invalid"])
67
+ def testCacheScenarios(pathCacheTesting: pathlib.Path, oeisID_1random: str, scenarioCache: str) -> None:
68
+ """Test cache scenarios: missing file, expired file, and invalid file."""
69
69
 
70
- def testCacheExpired(pathCacheTesting: pathlib.Path, oeisID_1random: str):
71
- """Test expired cache scenario."""
72
- def setupExpiredCache(pathCache: pathlib.Path, oeisID: str) -> None:
70
+ def setupCacheExpired(pathCache: pathlib.Path, oeisID: str) -> None:
73
71
  pathCache.write_text("# Old cache content")
74
72
  oldModificationTime = datetime.now() - timedelta(days=30)
75
73
  os.utime(pathCache, times=(oldModificationTime.timestamp(), oldModificationTime.timestamp()))
76
74
 
77
- standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], setupExpiredCache, oeisID_1random, pathCacheTesting)
78
-
79
- def testInvalidCache(pathCacheTesting: pathlib.Path, oeisID_1random: str):
80
- """Test invalid cache content scenario."""
81
- def setupInvalidCache(pathCache: pathlib.Path, oeisID: str) -> None:
75
+ def setupCacheInvalid(pathCache: pathlib.Path, oeisID: str) -> None:
82
76
  pathCache.write_text("Invalid content")
83
77
 
84
- standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], setupInvalidCache, oeisID_1random, pathCacheTesting)
78
+ if scenarioCache == "miss":
79
+ standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], None, oeisID_1random, pathCacheTesting)
80
+ elif scenarioCache == "expired":
81
+ standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], setupCacheExpired, oeisID_1random, pathCacheTesting)
82
+ else:
83
+ standardCacheTest(settingsOEIS[oeisID_1random]['valuesKnown'], setupCacheInvalid, oeisID_1random, pathCacheTesting)
85
84
 
86
85
  def testInvalidFileContent(pathCacheTesting: pathlib.Path, oeisID_1random: str):
87
- pathFilenameCache = pathCacheTesting / _formatFilenameCache.format(oeisID=oeisID_1random)
86
+ pathFilenameCache = pathCacheTesting / _getFilenameOEISbFile(oeisID=oeisID_1random)
88
87
 
89
88
  # Write invalid content to cache
90
89
  pathFilenameCache.write_text("# A999999\n1 1\n2 2\n")
@@ -100,25 +99,17 @@ def testInvalidFileContent(pathCacheTesting: pathlib.Path, oeisID_1random: str):
100
99
  # Verify cache now contains correct sequence ID
101
100
  assert f"# {oeisID_1random}" in pathFilenameCache.read_text()
102
101
 
103
- def testNetworkError(monkeypatch: pytest.MonkeyPatch, pathCacheTesting: pathlib.Path):
104
- def mockUrlopen(*args, **kwargs):
105
- raise urllib.error.URLError("Network error")
106
-
107
- monkeypatch.setattr(urllib.request, 'urlopen', mockUrlopen)
108
- with pytest.raises(urllib.error.URLError):
109
- _getOEISidValues(next(iter(settingsOEIS)))
110
-
111
102
  def testParseContentErrors():
112
103
  """Test invalid content parsing."""
113
104
  standardComparison(ValueError, _parseBFileOEIS, "Invalid content\n1 2\n", 'A001415')
114
105
 
115
106
  def testExtraComments(pathCacheTesting: pathlib.Path, oeisID_1random: str):
116
- pathFilenameCache = pathCacheTesting / _formatFilenameCache.format(oeisID=oeisID_1random)
107
+ pathFilenameCache = pathCacheTesting / _getFilenameOEISbFile(oeisID=oeisID_1random)
117
108
 
118
109
  # Write content with extra comment lines
119
110
  contentWithExtraComments = f"""# {oeisID_1random}
120
- # Extra comment line 1
121
- # Extra comment line 2
111
+ # Normal place for comment line 1
112
+ # Abnormal comment line
122
113
  1 2
123
114
  2 4
124
115
  3 6
@@ -133,6 +124,14 @@ def testExtraComments(pathCacheTesting: pathlib.Path, oeisID_1random: str):
133
124
  standardComparison(8, lambda d: d[4], OEISsequence) # Value after mid-sequence comment
134
125
  standardComparison(10, lambda d: d[5], OEISsequence) # Last value
135
126
 
127
+ def testNetworkError(monkeypatch: pytest.MonkeyPatch, pathCacheTesting: pathlib.Path):
128
+ """Test network error handling."""
129
+ def mockUrlopen(*args, **kwargs):
130
+ raise urllib.error.URLError("Network error")
131
+
132
+ monkeypatch.setattr(urllib.request, 'urlopen', mockUrlopen)
133
+ standardComparison(urllib.error.URLError, _getOEISidValues, next(iter(settingsOEIS)))
134
+
136
135
  # ===== Command Line Interface Tests =====
137
136
  def testHelpText():
138
137
  """Test that help text is complete and examples are valid."""
tests/test_other.py CHANGED
@@ -1,7 +1,12 @@
1
- from .conftest import *
1
+ from pathlib import Path
2
+ from typing import List, Optional, Dict, Any, Union
3
+ from tests.conftest import *
4
+ from tests.pythons_idiotic_namespace import *
2
5
  import pytest
3
6
  import sys
4
- # TODO test `outfitFoldings`, especially that `listDimensions` is sorted.
7
+ import unittest.mock
8
+ import numpy
9
+ import numba
5
10
 
6
11
  @pytest.mark.parametrize("listDimensions,expected_intInnit,expected_parseListDimensions,expected_validateListDimensions,expected_getLeavesTotal", [
7
12
  (None, ValueError, ValueError, ValueError, ValueError), # None instead of list
@@ -53,7 +58,35 @@ def test_getLeavesTotal_edge_cases() -> None:
53
58
  standardComparison(6, getLeavesTotal, listOriginal)
54
59
  standardComparison([2, 3], lambda x: x, listOriginal) # Check that the list wasn't modified
55
60
 
56
- # ===== Parse Integers Tests =====
61
+ @pytest.mark.parametrize("foldsValue,writeFoldsTarget", [
62
+ (756839, "foldsTotalTest.txt"), # Direct file
63
+ (2640919, "foldsTotalTest.txt"), # Direct file
64
+ (7715177, None), # Directory, will use default filename
65
+ ])
66
+ def test_countFolds_writeFoldsTotal(
67
+ listDimensionsTestFunctionality: List[int],
68
+ pathTempTesting: Path,
69
+ mockFoldingFunction,
70
+ foldsValue: int,
71
+ writeFoldsTarget: Optional[str]
72
+ ) -> None:
73
+ """Test writing folds total to either a file or directory."""
74
+ # For directory case, use the directory path directly
75
+ if writeFoldsTarget is None:
76
+ pathWriteTarget = pathTempTesting
77
+ filenameFoldsTotalExpected = getFilenameFoldsTotal(listDimensionsTestFunctionality)
78
+ else:
79
+ pathWriteTarget = pathTempTesting / writeFoldsTarget
80
+ filenameFoldsTotalExpected = writeFoldsTarget
81
+
82
+ mock_countFolds = mockFoldingFunction(foldsValue, listDimensionsTestFunctionality)
83
+
84
+ with unittest.mock.patch("mapFolding.babbage._countFolds", side_effect=mock_countFolds):
85
+ returned = countFolds(listDimensionsTestFunctionality, writeFoldsTotal=pathWriteTarget)
86
+
87
+ standardComparison(foldsValue, lambda: returned) # Check return value
88
+ standardComparison(str(foldsValue), lambda: (pathTempTesting / filenameFoldsTotalExpected).read_text()) # Check file content
89
+
57
90
  def test_intInnit() -> None:
58
91
  """Test integer parsing using the test suite generator."""
59
92
  for testName, testFunction in makeTestSuiteIntInnit(intInnit).items():
@@ -64,5 +97,102 @@ def test_oopsieKwargsie() -> None:
64
97
  for testName, testFunction in makeTestSuiteOopsieKwargsie(oopsieKwargsie).items():
65
98
  testFunction()
66
99
 
67
- def test_parseListDimensions_noDimensions() -> None:
68
- standardComparison(ValueError, parseDimensions, [])
100
+ # TODO mock CPU counts?
101
+ # @pytest.mark.parametrize("CPUlimit, expectedLimit", [
102
+ # (None, numba.config.NUMBA_DEFAULT_NUM_THREADS),
103
+ # (False, numba.config.NUMBA_DEFAULT_NUM_THREADS),
104
+ # (True, 1),
105
+ # (4, 4),
106
+ # (0.5, max(1, numba.config.NUMBA_DEFAULT_NUM_THREADS // 2)),
107
+ # (-0.5, max(1, numba.config.NUMBA_DEFAULT_NUM_THREADS // 2)),
108
+ # (-2, max(1, numba.config.NUMBA_DEFAULT_NUM_THREADS - 2)),
109
+ # ])
110
+ # def test_setCPUlimit(CPUlimit, expectedLimit) -> None:
111
+ # standardComparison(expectedLimit, setCPUlimit, CPUlimit)
112
+
113
+ def test_makeConnectionGraph_nonNegative(listDimensionsTestFunctionality: List[int]) -> None:
114
+ connectionGraph = makeConnectionGraph(listDimensionsTestFunctionality)
115
+ assert numpy.all(connectionGraph >= 0), "All values in the connection graph should be non-negative."
116
+
117
+ @pytest.mark.parametrize("datatype", [numpy.int16, numpy.uint64])
118
+ def test_makeConnectionGraph_datatype(listDimensionsTestFunctionality: List[int], datatype) -> None:
119
+ connectionGraph = makeConnectionGraph(listDimensionsTestFunctionality, datatype=datatype)
120
+ assert connectionGraph.dtype == datatype, f"Expected datatype {datatype}, but got {connectionGraph.dtype}."
121
+
122
+ # @pytest.mark.parametrize("computationDivisions,CPUlimit,datatypeOverrides", [
123
+ # (None, None, {}), # Basic case
124
+ # ("maximum", True, {"datatypeDefault": numpy.int32}), # Max divisions, min CPU, custom dtype
125
+ # ("cpu", 4, {"datatypeLarge": numpy.int64}), # CPU-based divisions, fixed CPU limit
126
+ # (3, 0.5, {}), # Fixed divisions, fractional CPU
127
+ # ])
128
+ # def test_outfitCountFolds(
129
+ # listDimensionsTestFunctionality: List[int],
130
+ # computationDivisions: Optional[Union[int, str]],
131
+ # CPUlimit: Optional[Union[bool, float, int]],
132
+ # datatypeOverrides: Dict[str, Any]
133
+ # ) -> None:
134
+ # """Test outfitCountFolds as a nexus of configuration and initialization.
135
+
136
+ # Strategy:
137
+ # 1. Validate structure against computationState TypedDict
138
+ # 2. Compare with direct function calls
139
+ # 3. Verify enum-based indexing
140
+ # 4. Check datatypes and shapes
141
+ # """
142
+ # # Get initialized state
143
+ # stateInitialized = outfitCountFolds(
144
+ # listDimensionsTestFunctionality,
145
+ # computationDivisions=computationDivisions,
146
+ # CPUlimit=CPUlimit,
147
+ # **datatypeOverrides
148
+ # )
149
+
150
+ # # 1. TypedDict structure validation
151
+ # for keyRequired in computationState.__annotations__:
152
+ # assert keyRequired in stateInitialized, f"Missing required key: {keyRequired}"
153
+ # assert stateInitialized[keyRequired] is not None, f"Key has None value: {keyRequired}"
154
+
155
+ # # Type checking
156
+ # expectedType = computationState.__annotations__[keyRequired]
157
+ # assert isinstance(stateInitialized[keyRequired], expectedType), \
158
+ # f"Type mismatch for {keyRequired}: expected {expectedType}, got {type(stateInitialized[keyRequired])}"
159
+
160
+ # # 2. Compare with direct function calls
161
+ # directMapShape = tuple(sorted(validateListDimensions(listDimensionsTestFunctionality)))
162
+ # assert stateInitialized['mapShape'] == directMapShape
163
+
164
+ # directConnectionGraph = makeConnectionGraph(
165
+ # directMapShape,
166
+ # datatype=datatypeOverrides.get('datatypeDefault', dtypeDefault)
167
+ # )
168
+ # assert numpy.array_equal(stateInitialized['connectionGraph'], directConnectionGraph)
169
+
170
+ # # 3. Enum-based indexing validation
171
+ # for arrayName, indexEnum in [
172
+ # ('my', indexMy),
173
+ # ('the', indexThe),
174
+ # ('track', indexTrack)
175
+ # ]:
176
+ # array = stateInitialized[arrayName]
177
+ # assert array.shape[0] >= len(indexEnum), \
178
+ # f"Array {arrayName} too small for enum {indexEnum.__name__}"
179
+
180
+ # # Test each enum index
181
+ # for enumMember in indexEnum:
182
+ # assert array[enumMember.value] >= 0, \
183
+ # f"Negative value at {arrayName}[{enumMember.name}]"
184
+
185
+ # # 4. Special value checks
186
+ # assert stateInitialized['my'][indexMy.leaf1ndex.value] == 1, \
187
+ # "Initial leaf index should be 1"
188
+
189
+ # # 5. Shape consistency
190
+ # leavesTotal = getLeavesTotal(listDimensionsTestFunctionality)
191
+ # assert stateInitialized['foldsSubTotals'].shape == (leavesTotal,), \
192
+ # "foldsSubTotals shape mismatch"
193
+ # assert stateInitialized['gapsWhere'].shape == (leavesTotal * leavesTotal + 1,), \
194
+ # "gapsWhere shape mismatch"
195
+ # assert stateInitialized['track'].shape == (len(indexTrack), leavesTotal + 1), \
196
+ # "track shape mismatch"
197
+
198
+ # TODO test `outfitCountFolds`; no negative values in arrays; compare datatypes to the typeddict; compare the connection graph to making a graph
tests/test_tasks.py CHANGED
@@ -3,6 +3,7 @@ import pytest
3
3
  from typing import List, Dict, Tuple
4
4
 
5
5
  # TODO add a test. `C` = number of logical cores available. `n = C + 1`. Ensure that `[2,n]` is computed correctly.
6
+ # Or, probably smarter: limit the number of cores, then run a test with C+1.
6
7
 
7
8
  def test_countFolds_computationDivisions(listDimensionsTest_countFolds: List[int], foldsTotalKnown: Dict[Tuple[int, ...], int]) -> None:
8
9
  standardComparison(foldsTotalKnown[tuple(listDimensionsTest_countFolds)], countFolds, listDimensionsTest_countFolds, None, 'maximum')
@@ -14,8 +15,17 @@ def test_defineConcurrencyLimit() -> None:
14
15
 
15
16
  @pytest.mark.parametrize("CPUlimitParameter", [{"invalid": True}, ["weird"]])
16
17
  def test_countFolds_cpuLimitOopsie(listDimensionsTestFunctionality: List[int], CPUlimitParameter: Dict[str, bool] | List[str]) -> None:
17
- # This forces CPUlimit = oopsieKwargsie(cpuLimitValue).
18
18
  standardComparison(ValueError, countFolds, listDimensionsTestFunctionality, None, 'cpu', CPUlimitParameter)
19
19
 
20
20
  def test_countFolds_invalid_computationDivisions(listDimensionsTestFunctionality: List[int]) -> None:
21
21
  standardComparison(ValueError, countFolds, listDimensionsTestFunctionality, None, {"wrong": "value"})
22
+
23
+ @pytest.mark.parametrize("computationDivisions, concurrencyLimit, listDimensions, expectedTaskDivisions", [
24
+ (None, 4, [9, 11], 0),
25
+ ("maximum", 4, [7, 11], 77),
26
+ ("cpu", 4, [3, 7], 4),
27
+ (["invalid"], 4, [19, 23], ValueError),
28
+ (20, 4, [3,5], ValueError)
29
+ ])
30
+ def test_getTaskDivisions(computationDivisions, concurrencyLimit, listDimensions, expectedTaskDivisions) -> None:
31
+ standardComparison(expectedTaskDivisions, getTaskDivisions, computationDivisions, concurrencyLimit, None, listDimensions)
@@ -1,5 +0,0 @@
1
- """Experiment"""
2
- from Z0Z_tools import defineConcurrencyLimit, intInnit, oopsieKwargsie
3
- from Z0Z_tools.pytest_parseParameters import makeTestSuiteConcurrencyLimit
4
- from Z0Z_tools.pytest_parseParameters import makeTestSuiteIntInnit
5
- from Z0Z_tools.pytest_parseParameters import makeTestSuiteOopsieKwargsie
@@ -1,28 +0,0 @@
1
- mapFolding/__init__.py,sha256=3kQQWyOBriVg9wO5btGE1Cq3lNqJz6CudrkOxVWcsy8,368
2
- mapFolding/babbage.py,sha256=3D1qcntoiJm2tqgbiCAMc7GpGA0SZTdGORNEnensyxk,1882
3
- mapFolding/beDRY.py,sha256=QACsmdskZplzMpYGUu7DSTSCE7x5JFApEyUqvUh0H0c,12613
4
- mapFolding/importPackages.py,sha256=Pno5VXaNiyJKG2Jtj4sB_h6EG50IJ7tQKyivVoKFMxo,303
5
- mapFolding/lovelace.py,sha256=qcyGpVEPP3n0r-RNrSUgPRP3yZJfBEfmok7jYMm1OI0,11473
6
- mapFolding/oeis.py,sha256=c8oCAcWgLvwC-bBZzGty8yth1vWtT8lWcKQeCiNGYgw,12078
7
- mapFolding/startHere.py,sha256=Z73A2bm35XygF6bpz710S8G2tVRdU_5-nO-nDgTaDhM,5068
8
- mapFolding/theSSOT.py,sha256=-t23-gPLPNWWBEeSi1mKkNCeeQA4y1AA_oPKC7tZwe4,1970
9
- mapFolding/JAX/lunnanJAX.py,sha256=xMZloN47q-MVfjdYOM1hi9qR4OnLq7qALmGLMraevQs,14819
10
- mapFolding/JAX/taskJAX.py,sha256=yJNeH0rL6EhJ6ppnATHF0Zf81CDMC10bnPnimVxE1hc,20037
11
- mapFolding/benchmarks/benchmarking.py,sha256=kv85F6V9pGhZvTOImArOuxyg5rywA_T6JLH_qFXM8BM,3018
12
- mapFolding/benchmarks/test_benchmarks.py,sha256=c4ANeR3jgqpKXFoxDeZkmAHxSuenMwsjmrhKJ1_XPqY,3659
13
- mapFolding/reference/hunterNumba.py,sha256=jV0dBjhLcnJjUHWRxLV_xvPIUP_GRLRKVeDhOtM9Wp4,7475
14
- mapFolding/reference/irvineJavaPort.py,sha256=Sj-63Z-OsGuDoEBXuxyjRrNmmyl0d7Yz_XuY7I47Oyg,4250
15
- mapFolding/reference/lunnan.py,sha256=SwjpOr1ROg-yZaZuiL7XjXhuvBxu_K4gQoPAWKUjJk4,5037
16
- mapFolding/reference/lunnanNumpy.py,sha256=bDQsBZUQcqJ9bTdnMF7HgtPcgpIodctujkm_lpq9NZ4,4653
17
- mapFolding/reference/lunnanWhile.py,sha256=p8_zLdMc6ujTYIu_yn-hbzOuLTQHvo0ENciIDmKayDU,4067
18
- mapFolding/reference/rotatedEntryPoint.py,sha256=6WVvEcGwDgRPa7dDs7ODAHUJjHDZDIDN6CXH8fFVFmA,12105
19
- tests/__init__.py,sha256=PGYVr7r23gATgcvZ3Sfph9D_g1MVvhgzMNWXBs_9tmY,52
20
- tests/conftest.py,sha256=ur6l5nDnWju7zOEMXqoNGYHY-Hf9GApOm4VT9pXtMtY,10594
21
- tests/test_oeis.py,sha256=h-NhWRoarl3v6qoB0RpnaUPuMGrQpWyfmsL0FXsGauU,7972
22
- tests/test_other.py,sha256=3Qc6fA39q5u_U0JhFUB9mdBd5_XcVC7IP9DwlNuG9p8,4716
23
- tests/test_tasks.py,sha256=Hn4N8OVVfDeNjL7ad5ELKKDgdOn8sDBj6IebPGpLIlE,1254
24
- mapFolding-0.2.1.dist-info/METADATA,sha256=r7QVig9M5_DReHsPG_wyyRNJe0UkggfUotMf8tfoF7I,5914
25
- mapFolding-0.2.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
26
- mapFolding-0.2.1.dist-info/entry_points.txt,sha256=F3OUeZR1XDTpoH7k3wXuRb3KF_kXTTeYhu5AGK1SiOQ,146
27
- mapFolding-0.2.1.dist-info/top_level.txt,sha256=1gP2vFaqPwHujGwb3UjtMlLEGN-943VSYFR7V4gDqW8,17
28
- mapFolding-0.2.1.dist-info/RECORD,,