Add tempdir and tempfile handling to AATest

Add writeTmpfile() to AATest to write a file into the tmpdir. If no
tmpdir exists yet, automatically create one.

createTmpdir() is a separate function so that it's possible to manually
create the tmpdir (for example, if a test needs an empty tmpdir).

Also add a tearDown() function to delete the tmpdir again. This function
calls self.AATeardown() to avoid the need for super() in child classes.

Finally, simplify AaTestWithTempdir in test-aa.py to use createTmpdir()
and add an example for AATeardown() to test-example.py.



Acked-by: Steve Beattie <steve@nxnw.org>
This commit is contained in:
Christian Boltz 2015-05-29 12:55:38 +02:00
parent 78505f3057
commit 5fa5125fd4
3 changed files with 27 additions and 9 deletions

View file

@ -16,7 +16,9 @@ import unittest
import inspect
import os
import re
import shutil
import sys
import tempfile
import apparmor.common
import apparmor.config
@ -47,7 +49,26 @@ class AATest(unittest.TestCase):
'''override this function if a test needs additional setup steps (instead of overriding setUp())'''
pass
def tearDown(self):
if self.tmpdir and os.path.exists(self.tmpdir):
shutil.rmtree(self.tmpdir)
self.AATeardown()
def AATeardown(self):
'''override this function if a test needs additional teardown steps (instead of overriding tearDown())'''
pass
def createTmpdir(self):
self.tmpdir = tempfile.mkdtemp(prefix='aa-test-')
def writeTmpfile(self, file, contents):
if not self.tmpdir:
self.createTmpdir()
return write_file(self.tmpdir, file, contents)
tests = []
tmpdir = None
class AAParseTest(unittest.TestCase):
parse_function = None

View file

@ -11,21 +11,14 @@
import unittest
from common_test import AATest, setup_all_loops
import os
import shutil
import tempfile
from common_test import read_file, write_file
from apparmor.aa import check_for_apparmor, get_profile_flags, set_profile_flags, is_skippable_file, is_skippable_dir, parse_profile_start, separate_vars, store_list_var, write_header, serialize_parse_profile_start
from apparmor.common import AppArmorException, AppArmorBug
class AaTestWithTempdir(AATest):
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix='aa-py-')
def tearDown(self):
if os.path.exists(self.tmpdir):
shutil.rmtree(self.tmpdir)
def AASetup(self):
self.createTmpdir()
class AaTest_check_for_apparmor(AaTestWithTempdir):

View file

@ -39,6 +39,10 @@ class TestBaz(AATest):
# called by setUp() - use AASetup() to avoid the need for using super(...)
pass
def AATeardown(self):
# called by tearDown() - use AATeardown() to avoid the need for using super(...)
pass
def test_Baz_only_one_test(self):
self.assertEqual("baz", "baz")