|
| 1 | +import os |
| 2 | +import ast |
| 3 | +import sys |
| 4 | +import json |
| 5 | +import tempfile |
| 6 | +import contextlib |
| 7 | +import subprocess |
| 8 | +import unittest.mock |
| 9 | + |
| 10 | +from dffml.util.os import chdir |
| 11 | + |
| 12 | + |
| 13 | +def sh_filepath(filename): |
| 14 | + return os.path.join(os.path.dirname(__file__), filename) |
| 15 | + |
| 16 | + |
| 17 | +@contextlib.contextmanager |
| 18 | +def directory_with_csv_files(): |
| 19 | + with tempfile.TemporaryDirectory() as tempdir: |
| 20 | + with chdir(tempdir): |
| 21 | + subprocess.check_output(["bash", sh_filepath("train_data.sh")]) |
| 22 | + subprocess.check_output(["bash", sh_filepath("test_data.sh")]) |
| 23 | + yield tempdir |
| 24 | + |
| 25 | + |
| 26 | +class TestExample(unittest.TestCase): |
| 27 | + def python_test(self, filename): |
| 28 | + # Path to target file |
| 29 | + filepath = os.path.join(os.path.dirname(__file__), filename) |
| 30 | + # Capture output |
| 31 | + stdout = subprocess.check_output([sys.executable, filepath]) |
| 32 | + lines = stdout.decode().split("\n") |
| 33 | + # Check the Accuracy |
| 34 | + self.assertIn("Accuracy: 0.9", lines[0]) |
| 35 | + # Check the classification |
| 36 | + self.assertEqual( |
| 37 | + round(ast.literal_eval(lines[1])["classification"]), 1 |
| 38 | + ) |
| 39 | + self.assertEqual( |
| 40 | + round(ast.literal_eval(lines[2])["classification"]), 2 |
| 41 | + ) |
| 42 | + |
| 43 | + def test_python_filenames(self): |
| 44 | + with directory_with_csv_files() as tempdir: |
| 45 | + self.python_test("tfdnnc.py") |
| 46 | + |
| 47 | + def test_shell(self): |
| 48 | + with directory_with_csv_files() as tempdir: |
| 49 | + # Run training |
| 50 | + subprocess.check_output(["bash", sh_filepath("train.sh")]) |
| 51 | + # Check the Accuracy |
| 52 | + stdout = subprocess.check_output( |
| 53 | + ["bash", sh_filepath("accuracy.sh")] |
| 54 | + ) |
| 55 | + self.assertAlmostEqual( |
| 56 | + float(stdout.decode().strip()), 0.9, places=0 |
| 57 | + ) |
| 58 | + # Make the prediction |
| 59 | + stdout = subprocess.check_output( |
| 60 | + ["bash", sh_filepath("predict.sh")] |
| 61 | + ) |
| 62 | + records = json.loads(stdout.decode()) |
| 63 | + # Check the classification |
| 64 | + self.assertAlmostEqual( |
| 65 | + round(records[0]["prediction"]["classification"]["value"]), 1 |
| 66 | + ) |
0 commit comments