From 48606f66d331a0b56613e21cb269fa29d2e32530 Mon Sep 17 00:00:00 2001 From: Pavel Kulyov Date: Thu, 23 Jul 2020 09:32:09 +0300 Subject: [PATCH] Add tests Signed-off-by: Pavel Kulyov --- tests/__init__.py | 0 tests/test_topsort.py | 81 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 tests/__init__.py create mode 100644 tests/test_topsort.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_topsort.py b/tests/test_topsort.py new file mode 100644 index 0000000..4c74531 --- /dev/null +++ b/tests/test_topsort.py @@ -0,0 +1,81 @@ +"""Unit tests for pytopsort module.""" + +import pytest + +from pytopsort import topsort + + +def test_topsort(): + """This recipe contains no cycles and can be sorted.""" + + # fmt: off + recipe = [{ + "action": "spread peanut butter on bread", + "after": ["slice bread"], + }, { + "action": "slice bread", + "after": [], + }, { + "action": "eat the delicious breakfast!", + "after": ["spread jam on top", "make a cup of coffee"], + }, { + "action": "make a cup of coffee", + "after": [], + }, { + "action": "spread jam on top", + "after": ["spread peanut butter on bread"], + }] + # fmt: on + + recipe = topsort( + recipe, deptest=lambda self, other: self["action"] in other["after"], + ) + + # fmt: off + assert list(recipe) == [{ + "action": "make a cup of coffee", + "after": [], + }, { + "action": "slice bread", + "after": [], + }, { + "action": "spread peanut butter on bread", + "after": ["slice bread"], + }, { + "action": "spread jam on top", + "after": ["spread peanut butter on bread"], + }, { + "action": "eat the delicious breakfast!", + "after": ["spread jam on top", "make a cup of coffee"], + }] + # fmt: on + + +def test_cycles(): + """This recipe contains a cycle (two actions depend on each other).""" + + # fmt: off + recipe = [{ + "action": "spread peanut butter on bread", + "after": ["slice bread"], + }, { + "action": "slice bread", + "after": ["spread peanut butter on bread"], + }, { + "action": "eat the delicious breakfast!", + "after": ["spread jam on top", "make a cup of coffee"], + }, { + "action": "make a cup of coffee", + "after": [], + }, { + "action": "spread jam on top", + "after": ["spread peanut butter on bread"], + }] + # fmt: on + + with pytest.raises(ValueError) as exc: + recipe = topsort( + recipe, deptest=lambda self, other: self["action"] in other["after"], + ) + + assert str(exc.value) == "Dependency graph has a cycle"