Coverage for /usr/local/lib/python3.8/site-packages/spam/helpers/test.py: 88%
32 statements
« prev ^ index » next coverage.py v7.2.3, created at 2023-11-22 13:26 +0000
« prev ^ index » next coverage.py v7.2.3, created at 2023-11-22 13:26 +0000
1# SPAM test class based on unitest.TestCase.
2# Copyright (C) 2020 SPAM Contributors
3#
4# This program is free software: you can redistribute it and/or modify it
5# under the terms of the GNU General Public License as published by the Free
6# Software Foundation, either version 3 of the License, or (at your option)
7# any later version.
8#
9# This program is distributed in the hope that it will be useful, but WITHOUT
10# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12# more details.
13#
14# You should have received a copy of the GNU General Public License along with
15# this program. If not, see <http://www.gnu.org/licenses/>.
17import os
18import shutil
19import time
20import unittest
21from pathlib import Path
23import numpy
26class TestSpam(unittest.TestCase):
27 """
28 Overwrites setUp and tearDown of unitest.TestCase
29 to create and delete a .dump folder for files created during tests.
30 """
32 # DEBUG mode
33 # if True:
34 # - deletes .dump/* before
35 # - does not delete .dump after
36 # can be modify in test file
37 # >>> if __name__ == "__main__":
38 # >>> spam.helpers.TestSpam.DEBUG = False
39 # >>> unittest.main()
40 DEBUG = False
42 def __init__(self, *args, **kwargs):
43 super().__init__(*args, **kwargs)
44 self.dump_folder = ".dump" if self.DEBUG else f".dump-{int(time.clock_gettime(0))}-{numpy.random.randint(65535)}"
46 def setUp(self):
47 # check if working directory is ".dump"
48 wd = os.getcwd()
49 if os.path.basename(wd) == self.dump_folder:
50 # we're already in ".dump"
51 pass
52 else:
53 # create .dump or delete .dump/*
54 d = os.path.join(wd, self.dump_folder)
55 if not os.path.isdir(d):
56 # print(f"TestSpam.setUp: create .dump directory {self.dump_folder}")
57 os.makedirs(d)
58 else:
59 for filename in os.listdir(d):
60 file_path = os.path.join(d, filename)
61 # print(f"TestSpam.setUp: delete file {file_path}")
62 os.remove(file_path)
63 os.chdir(d)
65 wd = os.getcwd()
67 def tearDown(self):
68 # check if working directory is ".dump"
69 wd = os.getcwd()
70 if os.path.basename(wd) == self.dump_folder:
71 # step back
72 d = Path(wd).resolve().parent
73 os.chdir(d)
75 else:
76 # print(f"TestSpam.tearDown: ERROR wrong working directory ({wd} instead of {self.dump_folder})")
77 # working directory is not ".dump" (that shouldn't happen)
78 pass
80 wd = os.getcwd()
82 # remove ".dump"
83 if not self.DEBUG:
84 if os.path.isdir(self.dump_folder):
85 # print(f"TestSpam.tearDown: delete .dump directory {self.dump_folder}")
86 shutil.rmtree(self.dump_folder)