pytorch/tools/test/heuristics/test_utils.py
Xuehai Pan b6bdb67f82 [BE][Easy] use pathlib.Path instead of dirname / ".." / pardir (#129374)
Changes by apply order:

1. Replace all `".."` and `os.pardir` usage with `os.path.dirname(...)`.
2. Replace nested `os.path.dirname(os.path.dirname(...))` call with `str(Path(...).parent.parent)`.
3. Reorder `.absolute()` ~/ `.resolve()`~ and `.parent`: always resolve the path first.

    `.parent{...}.absolute()` -> `.absolute().parent{...}`

4. Replace chained `.parent x N` with `.parents[${N - 1}]`: the code is easier to read (see 5.)

    `.parent.parent.parent.parent` -> `.parents[3]`

5. ~Replace `.parents[${N - 1}]` with `.parents[${N} - 1]`: the code is easier to read and does not introduce any runtime overhead.~

    ~`.parents[3]` -> `.parents[4 - 1]`~

6. ~Replace `.parents[2 - 1]` with `.parent.parent`: because the code is shorter and easier to read.~

Pull Request resolved: https://github.com/pytorch/pytorch/pull/129374
Approved by: https://github.com/justinchuby, https://github.com/malfet
2024-12-29 17:23:13 +00:00

59 lines
1.5 KiB
Python

from __future__ import annotations
import sys
import unittest
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parents[3]
sys.path.append(str(REPO_ROOT))
import tools.testing.target_determination.heuristics.utils as utils
from tools.testing.test_run import TestRun
sys.path.remove(str(REPO_ROOT))
class TestHeuristicsUtils(unittest.TestCase):
def assertDictAlmostEqual(
self, first: dict[TestRun, Any], second: dict[TestRun, Any]
) -> None:
self.assertEqual(first.keys(), second.keys())
for key in first.keys():
self.assertAlmostEqual(first[key], second[key])
def test_normalize_ratings(self) -> None:
ratings: dict[TestRun, float] = {
TestRun("test1"): 1,
TestRun("test2"): 2,
TestRun("test3"): 4,
}
normalized = utils.normalize_ratings(ratings, 4)
self.assertDictAlmostEqual(normalized, ratings)
normalized = utils.normalize_ratings(ratings, 0.1)
self.assertDictAlmostEqual(
normalized,
{
TestRun("test1"): 0.025,
TestRun("test2"): 0.05,
TestRun("test3"): 0.1,
},
)
normalized = utils.normalize_ratings(ratings, 0.2, min_value=0.1)
self.assertDictAlmostEqual(
normalized,
{
TestRun("test1"): 0.125,
TestRun("test2"): 0.15,
TestRun("test3"): 0.2,
},
)
if __name__ == "__main__":
unittest.main()