From 573ed5d407b8a573636000361753241b5b7c04ff Mon Sep 17 00:00:00 2001
From: Jan Kaluza <jkaluza@redhat.com>
Date: Jan 26 2018 10:37:38 +0000
Subject: Add tests.helpers.ModelsTestCase as base class for tests using Models. Use FreshmakerTestCase for other tests.


---

diff --git a/conf/config.py b/conf/config.py
index a7e5a2e..7fc1c22 100644
--- a/conf/config.py
+++ b/conf/config.py
@@ -248,8 +248,7 @@ class TestConfiguration(BaseConfiguration):
     LOG_LEVEL = 'debug'
     DEBUG = True
 
-    SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(
-        os.path.join(dbdir, 'tests', 'test_freshmaker.db'))
+    SQLALCHEMY_DATABASE_URI = 'sqlite://'
 
     MESSAGING = 'in_memory'
     MESSAGING_SENDER = 'in_memory'
diff --git a/tests/helpers.py b/tests/helpers.py
index 3cf10bf..77a6dda 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -26,6 +26,8 @@ import uuid
 import unittest
 
 from freshmaker import events
+from freshmaker import db
+from freshmaker.models import User
 
 
 BUILD_STATES = {
@@ -44,6 +46,27 @@ class FreshmakerTestCase(unittest.TestCase):
         return event
 
 
+class ModelsTestCase(FreshmakerTestCase):
+
+    def setUp(self):
+        super(ModelsTestCase, self).setUp()
+        db.session.remove()
+        db.drop_all()
+        db.create_all()
+        db.session.commit()
+
+        self.user = User(username='tester1')
+        db.session.add(self.user)
+        db.session.commit()
+
+    def tearDown(self):
+        super(ModelsTestCase, self).tearDown()
+
+        db.session.remove()
+        db.drop_all()
+        db.session.commit()
+
+
 class FedMsgFactory(object):
     def __init__(self, *args, **kwargs):
         self.msg_id = "%s-%s" % (time.strftime("%Y"), uuid.uuid4())
diff --git a/tests/test_auth.py b/tests/test_auth.py
index cb88b58..66454ea 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -23,7 +23,6 @@
 
 
 import flask
-import unittest
 
 from mock import patch, Mock
 
@@ -36,24 +35,10 @@ from freshmaker.auth import query_ldap_groups
 from freshmaker.errors import Unauthorized
 from freshmaker import app, db
 from freshmaker.models import User
+from tests.helpers import ModelsTestCase, FreshmakerTestCase
 
 
-class TestLoadKrbUserFromRequest(unittest.TestCase):
-
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-        self.user = User(username='tester1')
-        db.session.add(self.user)
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class TestLoadKrbUserFromRequest(ModelsTestCase):
 
     @patch('freshmaker.auth.query_ldap_groups')
     def test_create_new_user(self, query_ldap_groups):
@@ -102,22 +87,7 @@ class TestLoadKrbUserFromRequest(unittest.TestCase):
                 'REMOTE_USER is not present in request.' in ctx.exception.args)
 
 
-class TestLoadOpenIDCUserFromRequest(unittest.TestCase):
-
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-        self.user = User(username='tester1')
-        db.session.add(self.user)
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class TestLoadOpenIDCUserFromRequest(ModelsTestCase):
 
     @patch('freshmaker.auth.requests.get')
     def test_create_new_user(self, get):
@@ -220,7 +190,7 @@ class TestLoadOpenIDCUserFromRequest(unittest.TestCase):
                     ctx.exception.args)
 
 
-class TestQueryLdapGroups(unittest.TestCase):
+class TestQueryLdapGroups(FreshmakerTestCase):
     """Test auth.query_ldap_groups"""
 
     @patch('freshmaker.auth.ldap.initialize')
@@ -239,10 +209,12 @@ class TestQueryLdapGroups(unittest.TestCase):
                          sorted(groups))
 
 
-class TestInitAuth(unittest.TestCase):
+class TestInitAuth(FreshmakerTestCase):
     """Test init_auth"""
 
     def setUp(self):
+        super(FreshmakerTestCase, self).setUp()
+
         self.login_manager = Mock()
 
     def test_select_kerberos_auth_backend(self):
diff --git a/tests/test_bodhi_update_complete_stable_handler.py b/tests/test_bodhi_update_complete_stable_handler.py
index cb31cc8..5e9db1b 100644
--- a/tests/test_bodhi_update_complete_stable_handler.py
+++ b/tests/test_bodhi_update_complete_stable_handler.py
@@ -30,7 +30,7 @@ from tests import get_fedmsg
 
 import freshmaker
 
-from freshmaker import events, db, models
+from freshmaker import events, models
 from freshmaker.types import ArtifactType
 from freshmaker.handlers.bodhi import BodhiUpdateCompleteStableHandler
 from freshmaker.parsers.bodhi import BodhiUpdateCompleteStableParser
@@ -90,20 +90,11 @@ def mock_get_release_component_by_id(id):
     return mock_release_components[id]
 
 
-class BodhiUpdateCompleteStableHandlerTest(helpers.FreshmakerTestCase):
+class BodhiUpdateCompleteStableHandlerTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(BodhiUpdateCompleteStableHandlerTest, self).setUp()
         events.BaseEvent.register_parser(BodhiUpdateCompleteStableParser)
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @mock.patch('freshmaker.handlers.bodhi.update_complete_stable.PDC')
     @mock.patch('freshmaker.handlers.bodhi.update_complete_stable.utils')
     @mock.patch('freshmaker.handlers.bodhi.update_complete_stable.conf')
diff --git a/tests/test_brew_container_task_state_change_handler.py b/tests/test_brew_container_task_state_change_handler.py
index d63b75e..ae50525 100644
--- a/tests/test_brew_container_task_state_change_handler.py
+++ b/tests/test_brew_container_task_state_change_handler.py
@@ -33,21 +33,12 @@ from freshmaker.handlers.brew import BrewContainerTaskStateChangeHandler
 from freshmaker.types import ArtifactType, ArtifactBuildState, EventState
 
 
-class TestBrewContainerTaskStateChangeHandler(helpers.FreshmakerTestCase):
+class TestBrewContainerTaskStateChangeHandler(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(TestBrewContainerTaskStateChangeHandler, self).setUp()
         events.BaseEvent.register_parser(BrewTaskStateChangeParser)
         self.handler = BrewContainerTaskStateChangeHandler()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_can_handle_brew_container_task_closed_event(self):
         """
         Tests handler can handle brew build container task closed event.
diff --git a/tests/test_brew_sign_rpm_handler.py b/tests/test_brew_sign_rpm_handler.py
index 6bf1589..9934b21 100644
--- a/tests/test_brew_sign_rpm_handler.py
+++ b/tests/test_brew_sign_rpm_handler.py
@@ -21,29 +21,16 @@
 #
 # Written by Chenxiong Qi <cqi@redhat.com>
 
-import unittest
-
 from mock import patch, MagicMock, PropertyMock
 
 from freshmaker.handlers.brew.sign_rpm import BrewSignRPMHandler
 from freshmaker.errata import ErrataAdvisory
-from freshmaker import db
+from tests import helpers
 
 
-class TestBrewSignHandler(unittest.TestCase):
+class TestBrewSignHandler(helpers.ModelsTestCase):
     """Test BrewSignRPMHandler.handle"""
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @patch('freshmaker.errata.Errata.advisories_from_event')
     @patch('freshmaker.errata.Errata.builds_signed')
     @patch("freshmaker.config.Config.handler_build_whitelist",
diff --git a/tests/test_consumer.py b/tests/test_consumer.py
index 0fa5e1e..8c94ef2 100644
--- a/tests/test_consumer.py
+++ b/tests/test_consumer.py
@@ -29,9 +29,10 @@ from freshmaker.models import Event, ArtifactBuild
 from freshmaker import db
 from freshmaker.types import ArtifactBuildState
 from freshmaker.handlers import fail_event_on_handler_exception
+from tests import helpers
 
 
-class ConsumerBaseTest(unittest.TestCase):
+class ConsumerBaseTest(helpers.ModelsTestCase):
 
     def _create_consumer(self):
         hub = mock.MagicMock()
@@ -56,17 +57,6 @@ class ConsumerBaseTest(unittest.TestCase):
 
 class ConsumerTest(ConsumerBaseTest):
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @mock.patch("freshmaker.handlers.mbs.module_state_change.MBSModuleStateChangeHandler.handle")
     @mock.patch("freshmaker.consumer.get_global_consumer")
     def test_consumer_processing_message(self, global_consumer, handle):
diff --git a/tests/test_errata.py b/tests/test_errata.py
index d133bbe..406f74c 100644
--- a/tests/test_errata.py
+++ b/tests/test_errata.py
@@ -20,13 +20,12 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 # SOFTWARE.
 
-import unittest
-
 from mock import patch
 
 from freshmaker.errata import Errata
 from freshmaker.events import (
     BrewSignRPMEvent, GitRPMSpecChangeEvent, ErrataAdvisoryStateChangedEvent)
+from tests import helpers
 
 
 class MockedErrataAPI(object):
@@ -112,8 +111,9 @@ class MockedErrataAPI(object):
                 return self.product_versions[id]
 
 
-class TestErrata(unittest.TestCase):
+class TestErrata(helpers.FreshmakerTestCase):
     def setUp(self):
+        super(TestErrata, self).setUp()
         self.errata = Errata("https://localhost/")
 
     @patch.object(Errata, "_errata_rest_get")
diff --git a/tests/test_errata_advisory_rpms_signed_handler.py b/tests/test_errata_advisory_rpms_signed_handler.py
index 1789d58..d11007d 100644
--- a/tests/test_errata_advisory_rpms_signed_handler.py
+++ b/tests/test_errata_advisory_rpms_signed_handler.py
@@ -19,7 +19,6 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 # SOFTWARE.
 
-import unittest
 import requests
 
 from mock import patch
@@ -32,15 +31,13 @@ from freshmaker.handlers.errata import ErrataAdvisoryRPMsSignedHandler
 from freshmaker.lightblue import ContainerImage
 from freshmaker.models import Event, Compose
 from freshmaker.types import EventState
+from tests import helpers
 
 
-class TestErrataAdvisoryRPMsSignedHandler(unittest.TestCase):
+class TestErrataAdvisoryRPMsSignedHandler(helpers.ModelsTestCase):
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestErrataAdvisoryRPMsSignedHandler, self).setUp()
 
         # We do not want to send messages to message bus while running tests
         self.messaging_publish_patcher = patch('freshmaker.messaging.publish')
@@ -197,15 +194,12 @@ class TestErrataAdvisoryRPMsSignedHandler(unittest.TestCase):
         ])
 
     def tearDown(self):
+        super(TestErrataAdvisoryRPMsSignedHandler, self).tearDown()
         self.request_boot_iso_compose_patcher.stop()
         self.find_images_patcher.stop()
         self.prepare_pulp_repo_patcher.stop()
         self.messaging_publish_patcher.stop()
 
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @patch.object(freshmaker.conf, 'handler_build_whitelist', new={
         'ErrataAdvisoryRPMsSignedHandler': {
             'image': [{'product_short_name': 'foo'}]
@@ -329,10 +323,12 @@ class TestErrataAdvisoryRPMsSignedHandler(unittest.TestCase):
         self.assertEqual(EventState.BUILDING.value, db_event.state)
 
 
-class TestGetBaseImageBuildTarget(unittest.TestCase):
+class TestGetBaseImageBuildTarget(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._get_base_image_build_target"""
 
     def setUp(self):
+        super(TestGetBaseImageBuildTarget, self).setUp()
+
         self.image = ContainerImage({
             'repository': 'repo_1',
             'commit': '1234567',
@@ -401,10 +397,12 @@ ksversion = RHEL7'''
         self.assertIsNone(result)
 
 
-class TestGetBaseImageBuildTag(unittest.TestCase):
+class TestGetBaseImageBuildTag(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._get_base_image_build_tag"""
 
     def setUp(self):
+        super(TestGetBaseImageBuildTag, self).setUp()
+
         self.image = ContainerImage({
             'repository': 'repo_1',
             'commit': '1234567',
@@ -458,10 +456,12 @@ class TestGetBaseImageBuildTag(unittest.TestCase):
         self.assertIsNone(result)
 
 
-class TestRequestBootISOCompose(unittest.TestCase):
+class TestRequestBootISOCompose(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._request_boot_iso_compose"""
 
     def setUp(self):
+        super(TestRequestBootISOCompose, self).setUp()
+
         self.image = ContainerImage({
             'repository': 'repo_1',
             'commit': '1234567',
@@ -532,9 +532,11 @@ class TestRequestBootISOCompose(unittest.TestCase):
         self.assertIsNone(result)
 
 
-class TestErrataAdvisoryRPMsSignedHandler(unittest.TestCase):
+class TestFindImagesToRebuild(helpers.FreshmakerTestCase):
 
     def setUp(self):
+        super(TestFindImagesToRebuild, self).setUp()
+
         self.get_content_set_by_repo_ids_patcher = patch(
             'freshmaker.pulp.Pulp.get_content_set_by_repo_ids')
         self.get_content_set_by_repo_ids = self.get_content_set_by_repo_ids_patcher.start()
@@ -567,6 +569,8 @@ class TestErrataAdvisoryRPMsSignedHandler(unittest.TestCase):
         self.handler.event = self.event
 
     def tearDown(self):
+        super(TestFindImagesToRebuild, self).tearDown()
+
         self.get_content_set_by_repo_ids_patcher.stop()
         self.get_pulp_repository_ids_patcher.stop()
         self.get_builds_patcher.stop()
diff --git a/tests/test_errata_advisory_state_changed.py b/tests/test_errata_advisory_state_changed.py
index 00d7904..8119a7f 100644
--- a/tests/test_errata_advisory_state_changed.py
+++ b/tests/test_errata_advisory_state_changed.py
@@ -35,9 +35,10 @@ from freshmaker.handlers.errata import ErrataAdvisoryStateChangedHandler
 from freshmaker.lightblue import ContainerImage
 from freshmaker.models import Event, ArtifactBuild, EVENT_TYPES
 from freshmaker.types import ArtifactBuildState, ArtifactType, EventState
+from tests import helpers
 
 
-class TestFindBuildSrpmName(unittest.TestCase):
+class TestFindBuildSrpmName(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._find_build_srpm_name"""
 
     @patch('koji.ClientSession')
@@ -86,20 +87,9 @@ class TestFindBuildSrpmName(unittest.TestCase):
         session.listRPMs.assert_called_once_with(buildID=439408, arches='src')
 
 
-class TestAllowBuild(unittest.TestCase):
+class TestAllowBuild(helpers.ModelsTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler.allow_build"""
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @patch("freshmaker.handlers.errata.ErrataAdvisoryRPMsSignedHandler."
            "_find_images_to_rebuild", return_value=[])
     @patch("freshmaker.config.Config.handler_build_whitelist",
@@ -254,20 +244,9 @@ class TestAllowBuild(unittest.TestCase):
         self.assertEqual(ret, True)
 
 
-class TestBatches(unittest.TestCase):
+class TestBatches(helpers.ModelsTestCase):
     """Test handling of batches"""
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def _mock_build(self, build, parent=None, error=None):
         if parent:
             parent = {"brew": {"build": parent + "-1-1.25"}}
@@ -360,14 +339,11 @@ class TestBatches(unittest.TestCase):
                              build.dep_on.rebuilt_nvr if build.dep_on else None)
 
 
-class TestCheckImagesToRebuild(unittest.TestCase):
+class TestCheckImagesToRebuild(helpers.ModelsTestCase):
     """Test handling of batches"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestCheckImagesToRebuild, self).setUp()
 
         build_args = json.dumps({
             "parent": "nvr",
@@ -395,11 +371,6 @@ class TestCheckImagesToRebuild(unittest.TestCase):
         self.b2.build_args = build_args
         db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_check_images_to_rebuild(self):
         builds = {
             "parent-1-25": self.b1,
@@ -448,7 +419,7 @@ class TestCheckImagesToRebuild(unittest.TestCase):
             self.assertEqual(build.state, ArtifactBuildState.FAILED.value)
 
 
-class TestGetPackagesForCompose(unittest.TestCase):
+class TestGetPackagesForCompose(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._get_packages_for_compose"""
 
     @patch('freshmaker.kojiservice.KojiService.get_build_rpms')
@@ -490,7 +461,7 @@ class TestGetPackagesForCompose(unittest.TestCase):
                          set(packages))
 
 
-class TestGetComposeSource(unittest.TestCase):
+class TestGetComposeSource(helpers.FreshmakerTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._get_compose_source"""
 
     @patch('freshmaker.kojiservice.KojiService.session', callable=PropertyMock)
@@ -602,14 +573,11 @@ class TestGetComposeSource(unittest.TestCase):
         self.assertEqual('rhel-6-candidate', tag)
 
 
-class TestPrepareYumRepo(unittest.TestCase):
+class TestPrepareYumRepo(helpers.ModelsTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._prepare_yum_repo"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestPrepareYumRepo, self).setUp()
 
         self.ev = Event.create(db.session, 'msg-id', '123', 100)
         ArtifactBuild.create(
@@ -617,11 +585,6 @@ class TestPrepareYumRepo(unittest.TestCase):
             state=ArtifactBuildState.PLANNED)
         db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @patch('freshmaker.handlers.errata.errata_advisory_rpms_signed.'
            'create_odcs_client')
     @patch('freshmaker.handlers.errata.errata_advisory_rpms_signed.'
@@ -732,18 +695,7 @@ class TestPrepareYumRepo(unittest.TestCase):
                 "of advisory 123 is the latest build in its candidate tag."))
 
 
-class TestErrataAdvisoryStateChangedHandler(unittest.TestCase):
-
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class TestErrataAdvisoryStateChangedHandler(helpers.ModelsTestCase):
 
     @patch('freshmaker.errata.Errata.advisories_from_event')
     def test_rebuild_if_not_exists(self, advisories_from_event):
@@ -909,14 +861,11 @@ class TestErrataAdvisoryStateChangedHandler(unittest.TestCase):
         self.assertEqual(len(msgs), 1)
 
 
-class TestRecordBatchesImages(unittest.TestCase):
+class TestRecordBatchesImages(helpers.ModelsTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._record_batches"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestRecordBatchesImages, self).setUp()
 
         self.mock_event = Mock(msg_id='msg-id', search_key=12345)
 
@@ -938,14 +887,12 @@ class TestRecordBatchesImages(unittest.TestCase):
             self.request_boot_iso_compose_patcher.start()
 
     def tearDown(self):
+        super(TestRecordBatchesImages, self).tearDown()
+
         self.request_boot_iso_compose_patcher.stop()
         self.prepare_pulp_repo_patcher.stop()
         self.event_types_patcher.stop()
 
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_record_batches(self):
         batches = [
             [ContainerImage({
@@ -1268,14 +1215,11 @@ class TestRecordBatchesImages(unittest.TestCase):
         self.mock_prepare_pulp_repo.assert_not_called()
 
 
-class TestPrepareYumReposForRebuilds(unittest.TestCase):
+class TestPrepareYumReposForRebuilds(helpers.ModelsTestCase):
     """Test ErrataAdvisoryRPMsSignedHandler._prepare_yum_repos_for_rebuilds"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestPrepareYumReposForRebuilds, self).setUp()
 
         self.prepare_yum_repo_patcher = patch(
             'freshmaker.handlers.errata.errata_advisory_rpms_signed.'
@@ -1306,13 +1250,11 @@ class TestPrepareYumReposForRebuilds(unittest.TestCase):
         db.session.commit()
 
     def tearDown(self):
+        super(TestPrepareYumReposForRebuilds, self).tearDown()
+
         self.find_dependent_event_patcher.stop()
         self.prepare_yum_repo_patcher.stop()
 
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_prepare_without_dependent_events(self):
         self.mock_find_dependent_event.return_value = []
 
@@ -1345,7 +1287,7 @@ class TestPrepareYumReposForRebuilds(unittest.TestCase):
         ], sorted(urls))
 
 
-class TestSkipNonRPMAdvisory(unittest.TestCase):
+class TestSkipNonRPMAdvisory(helpers.FreshmakerTestCase):
 
     def test_ensure_to_handle_rpm_adivsory(self):
         event = ErrataAdvisoryStateChangedEvent(
diff --git a/tests/test_freshmaker_manual_rebuild_handler.py b/tests/test_freshmaker_manual_rebuild_handler.py
index 8fa59cd..ff8bcfc 100644
--- a/tests/test_freshmaker_manual_rebuild_handler.py
+++ b/tests/test_freshmaker_manual_rebuild_handler.py
@@ -21,31 +21,18 @@
 #
 # Written by Chenxiong Qi <cqi@redhat.com>
 
-import unittest
-
 from mock import patch
 
 from freshmaker.handlers.internal import FreshmakerManualRebuildHandler
 from freshmaker.events import FreshmakerManualRebuildEvent
 
 from freshmaker.errata import ErrataAdvisory
-from freshmaker import db
 from freshmaker.models import Event
 from freshmaker.types import EventState
+from tests import helpers
 
 
-class TestFreshmakerManualRebuildHandler(unittest.TestCase):
-
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class TestFreshmakerManualRebuildHandler(helpers.ModelsTestCase):
 
     @patch('freshmaker.errata.Errata.advisories_from_event')
     def test_rebuild_if_not_exists(self, advisories_from_event):
diff --git a/tests/test_git_dockerfile_change_handler.py b/tests/test_git_dockerfile_change_handler.py
index 3dfe71e..1655ddf 100644
--- a/tests/test_git_dockerfile_change_handler.py
+++ b/tests/test_git_dockerfile_change_handler.py
@@ -20,8 +20,6 @@
 #
 # Written by Chenxiong Qi <cqi@redhat.com>
 
-import unittest
-
 import fedmsg.config
 
 from mock import patch
@@ -29,23 +27,13 @@ from mock import MagicMock, PropertyMock
 
 import freshmaker
 
-from freshmaker import db, models
+from freshmaker import models
 from freshmaker.consumer import FreshmakerConsumer
 from freshmaker.types import ArtifactType
-from tests import get_fedmsg
-
+from tests import get_fedmsg, helpers
 
-class BaseTestCase(unittest.TestCase):
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class BaseTestCase(helpers.ModelsTestCase):
 
     def create_consumer(self):
         hub = MagicMock()
diff --git a/tests/test_git_module_metadata_change_handler.py b/tests/test_git_module_metadata_change_handler.py
index 1b5fd38..a916b13 100644
--- a/tests/test_git_module_metadata_change_handler.py
+++ b/tests/test_git_module_metadata_change_handler.py
@@ -28,26 +28,17 @@ from tests import helpers
 
 import freshmaker
 
-from freshmaker import events, db, models
+from freshmaker import events, models
 from freshmaker.types import ArtifactType
 from freshmaker.handlers.git import GitModuleMetadataChangeHandler
 from freshmaker.parsers.git import GitReceiveParser
 
 
-class GitModuleMetadataChangeHandlerTest(helpers.FreshmakerTestCase):
+class GitModuleMetadataChangeHandlerTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(GitModuleMetadataChangeHandlerTest, self).setUp()
         events.BaseEvent.register_parser(GitReceiveParser)
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_can_handle_module_metadata_change_event(self):
         """
         Tests handler can handle module metadata change message
diff --git a/tests/test_git_rpm_spec_change_handler.py b/tests/test_git_rpm_spec_change_handler.py
index 236debb..568e21c 100644
--- a/tests/test_git_rpm_spec_change_handler.py
+++ b/tests/test_git_rpm_spec_change_handler.py
@@ -28,26 +28,17 @@ from tests import helpers
 
 import freshmaker
 
-from freshmaker import events, db, models
+from freshmaker import events, models
 from freshmaker.types import ArtifactType
 from freshmaker.handlers.git import GitRPMSpecChangeHandler
 from freshmaker.parsers.git import GitReceiveParser
 
 
-class GitRPMSpecChangeHandlerTest(helpers.FreshmakerTestCase):
+class GitRPMSpecChangeHandlerTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(GitRPMSpecChangeHandlerTest, self).setUp()
         events.BaseEvent.register_parser(GitReceiveParser)
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_can_handle_dist_git_message_with_rpm_spec_changed(self):
         """
         Tests handler can handle rpm spec change event
diff --git a/tests/test_handler.py b/tests/test_handler.py
index cc6d271..11dc56c 100644
--- a/tests/test_handler.py
+++ b/tests/test_handler.py
@@ -23,7 +23,6 @@
 # Written by Chenxiong Qi <cqi@redhat.com>
 
 from mock import patch, PropertyMock
-from unittest import TestCase
 
 import freshmaker
 
@@ -36,6 +35,7 @@ from freshmaker.models import (
 )
 from freshmaker.errors import UnprocessableEntity, ProgrammingError
 from freshmaker.types import ArtifactType, EventState
+from tests import helpers
 
 
 class MyHandler(ContainerBuildHandler):
@@ -50,14 +50,16 @@ class MyHandler(ContainerBuildHandler):
         """Implement BaseHandler method"""
 
 
-class TestKrbContextPreparedForBuildContainer(TestCase):
+class TestKrbContextPreparedForBuildContainer(helpers.FreshmakerTestCase):
     """Test krb_context for BaseHandler.build_container"""
 
     def setUp(self):
+        super(TestKrbContextPreparedForBuildContainer, self).setUp()
         self.koji_service = patch('freshmaker.kojiservice.KojiService')
         self.koji_service.start()
 
     def tearDown(self):
+        super(TestKrbContextPreparedForBuildContainer, self).tearDown()
         self.koji_service.stop()
 
     @patch('freshmaker.utils.conf')
@@ -98,20 +100,9 @@ class TestKrbContextPreparedForBuildContainer(TestCase):
         )
 
 
-class TestContext(TestCase):
+class TestContext(helpers.ModelsTestCase):
     """Test setting context of handler"""
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_context_event(self):
         db_event = Event.get_or_create(
             db.session, "msg1", "current_event", ErrataAdvisoryRPMsSignedEvent)
@@ -139,13 +130,10 @@ class TestContext(TestCase):
         self.assertRaises(ProgrammingError, handler.set_context, "something")
 
 
-class TestGetRepoURLs(TestCase):
+class TestGetRepoURLs(helpers.ModelsTestCase):
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestGetRepoURLs, self).setUp()
 
         self.compose_1 = Compose(odcs_compose_id=1)
         self.compose_2 = Compose(odcs_compose_id=2)
@@ -208,9 +196,7 @@ class TestGetRepoURLs(TestCase):
         self.odcs_get_compose = self.patch_odcs_get_compose.start()
 
     def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+        super(TestGetRepoURLs, self).tearDown()
         self.patch_odcs_get_compose.stop()
 
     def test_get_repo_urls_no_composes(self):
@@ -231,7 +217,7 @@ class TestGetRepoURLs(TestCase):
             sorted(repos))
 
 
-class TestAllowBuildBasedOnWhitelist(TestCase):
+class TestAllowBuildBasedOnWhitelist(helpers.FreshmakerTestCase):
     """Test BaseHandler.allow_build"""
 
     @patch('freshmaker.handlers.conf')
diff --git a/tests/test_koji_task_state_change_handler.py b/tests/test_koji_task_state_change_handler.py
index 0f9462d..5ea8cd4 100644
--- a/tests/test_koji_task_state_change_handler.py
+++ b/tests/test_koji_task_state_change_handler.py
@@ -31,20 +31,11 @@ from freshmaker.handlers.koji import KojiTaskStateChangeHandler
 from freshmaker.parsers.koji import KojiTaskStateChangeParser
 
 
-class KojiTaskStateChangeHandlerTest(helpers.FreshmakerTestCase):
+class KojiTaskStateChangeHandlerTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(KojiTaskStateChangeHandlerTest, self).setUp()
         events.BaseEvent.register_parser(KojiTaskStateChangeParser)
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_can_handle_koji_task_state_change_message(self):
         """
         Tests buildsys handler can handle koji task state changed message
diff --git a/tests/test_lightblue.py b/tests/test_lightblue.py
index db07b28..0d53f14 100644
--- a/tests/test_lightblue.py
+++ b/tests/test_lightblue.py
@@ -22,7 +22,6 @@
 
 import json
 import six
-import unittest
 
 from mock import call, patch, Mock
 from six.moves import http_client
@@ -32,12 +31,14 @@ from freshmaker.lightblue import ContainerRepository
 from freshmaker.lightblue import LightBlue
 from freshmaker.lightblue import LightBlueRequestError
 from freshmaker.lightblue import LightBlueSystemError
+from tests import helpers
 
 
-class TestLightBlueRequestError(unittest.TestCase):
+class TestLightBlueRequestError(helpers.FreshmakerTestCase):
     """Test case for exception LightBlueRequestError"""
 
     def setUp(self):
+        super(TestLightBlueRequestError, self).setUp()
         self.fake_error_data = {
             'entity': 'containerImage',
             'entityVersion': '0.0.11',
@@ -73,10 +74,11 @@ class TestLightBlueRequestError(unittest.TestCase):
         self.assertIn(expected_s, str(self.e))
 
 
-class TestLightBlueSystemError(unittest.TestCase):
+class TestLightBlueSystemError(helpers.FreshmakerTestCase):
     """Test LightBlueSystemError"""
 
     def setUp(self):
+        super(TestLightBlueSystemError, self).setUp()
         buf = six.StringIO('''
 <html><head><title>JBWEB000065: HTTP Status 401 - JBWEB000009: No client
 certificate chain in this request</title><style><!--H1 {font-family:Tahoma,
@@ -117,7 +119,7 @@ description</b> <u>JBWEB000121: This request requires HTTP authentication.</u>
                          repr(self.e))
 
 
-class TestContainerImageObject(unittest.TestCase):
+class TestContainerImageObject(helpers.FreshmakerTestCase):
 
     def test_create(self):
         image = ContainerImage.create({
@@ -305,7 +307,7 @@ class TestContainerImageObject(unittest.TestCase):
         self.assertEqual(image["content_sets"], [])
 
 
-class TestContainerRepository(unittest.TestCase):
+class TestContainerRepository(helpers.FreshmakerTestCase):
 
     def test_create(self):
         image = ContainerRepository.create({
@@ -321,9 +323,10 @@ class TestContainerRepository(unittest.TestCase):
         self.assertEqual('20170223T08:28:40.913-0500', image['metrics']['last_update_date'])
 
 
-class TestQueryEntityFromLightBlue(unittest.TestCase):
+class TestQueryEntityFromLightBlue(helpers.FreshmakerTestCase):
 
     def setUp(self):
+        super(TestQueryEntityFromLightBlue, self).setUp()
         # Clear the ContainerImage Koji cache.
         ContainerImage.KOJI_BUILDS_CACHE = {}
 
@@ -1065,10 +1068,11 @@ class TestQueryEntityFromLightBlue(unittest.TestCase):
                 ["dummy-content-set-1"])
 
 
-class TestEntityVersion(unittest.TestCase):
+class TestEntityVersion(helpers.FreshmakerTestCase):
     """Test case for ensuring correct entity version in request"""
 
     def setUp(self):
+        super(TestEntityVersion, self).setUp()
         self.fake_server_url = 'lightblue.localhost'
         self.fake_cert_file = 'path/to/cert'
         self.fake_private_key = 'path/to/private-key'
diff --git a/tests/test_mbs_module_state_change_handler.py b/tests/test_mbs_module_state_change_handler.py
index a3fa914..2c53db4 100644
--- a/tests/test_mbs_module_state_change_handler.py
+++ b/tests/test_mbs_module_state_change_handler.py
@@ -34,20 +34,11 @@ from freshmaker.handlers.mbs import MBSModuleStateChangeHandler
 from freshmaker.parsers.mbs import MBSModuleStateChangeParser
 
 
-class MBSModuleStateChangeHandlerTest(helpers.FreshmakerTestCase):
+class MBSModuleStateChangeHandlerTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(MBSModuleStateChangeHandlerTest, self).setUp()
         events.BaseEvent.register_parser(MBSModuleStateChangeParser)
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_can_handle_module_state_change_event(self):
         """
         Tests MBS handler can handle module built message
diff --git a/tests/test_messaging.py b/tests/test_messaging.py
index 80ebb45..233866c 100644
--- a/tests/test_messaging.py
+++ b/tests/test_messaging.py
@@ -29,6 +29,7 @@ from mock import patch
 from freshmaker import conf
 from freshmaker import messaging
 from freshmaker.messaging import publish
+from tests import helpers
 
 try:
     import rhmsg
@@ -36,13 +37,15 @@ except ImportError:
     rhmsg = None
 
 
-class BaseMessagingTest(unittest.TestCase):
+class BaseMessagingTest(helpers.FreshmakerTestCase):
     """ Base class for messaging related tests """
 
     def setUp(self):
+        super(BaseMessagingTest, self).setUp()
         messaging._in_memory_msg_id = 0
 
     def tearDown(self):
+        super(BaseMessagingTest, self).tearDown()
         messaging._in_memory_msg_id = 0
 
 
diff --git a/tests/test_models.py b/tests/test_models.py
index ec2245b..6071add 100644
--- a/tests/test_models.py
+++ b/tests/test_models.py
@@ -20,27 +20,16 @@
 #
 # Written by Jan Kaluza <jkaluza@redhat.com>
 
-import unittest
-
 from freshmaker import db, events
 from freshmaker.models import ArtifactBuild, ArtifactType
 from freshmaker.models import Event, EventState, EVENT_TYPES, EventDependency
 from freshmaker.models import Compose, ArtifactBuildCompose
 from freshmaker.types import ArtifactBuildState
 from freshmaker.events import ErrataAdvisoryRPMsSignedEvent
+from tests import helpers
 
 
-class TestModels(unittest.TestCase):
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+class TestModels(helpers.ModelsTestCase):
 
     def test_creating_event_and_builds(self):
         event = Event.create(db.session, "test_msg_id", "RHSA-2017-284", events.TestingEvent)
@@ -169,14 +158,11 @@ class TestModels(unittest.TestCase):
             str(event), "<UnknownEventType 1024, search_key=test>")
 
 
-class TestFindDependentEvents(unittest.TestCase):
+class TestFindDependentEvents(helpers.ModelsTestCase):
     """Test Event.find_dependent_events"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestFindDependentEvents, self). setUp()
 
         self.event_1 = Event.create(
             db.session, 'msg-1', 'search-key-1',
@@ -249,11 +235,6 @@ class TestFindDependentEvents(unittest.TestCase):
 
         db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_find_dependent_events(self):
         dep_events = self.event_1.find_dependent_events()
         self.assertEqual([self.event_2.id, self.event_3.id],
@@ -267,14 +248,11 @@ class TestFindDependentEvents(unittest.TestCase):
         self.assertIn((self.event_1.id, self.event_3.id), dep_rels)
 
 
-class TestArtifactBuildComposesRel(unittest.TestCase):
+class TestArtifactBuildComposesRel(helpers.ModelsTestCase):
     """Test m2m relationship between ArtifactBuild and Compose"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestArtifactBuildComposesRel, self). setUp()
 
         self.compose_1 = Compose(odcs_compose_id=1)
         self.compose_2 = Compose(odcs_compose_id=2)
@@ -314,11 +292,6 @@ class TestArtifactBuildComposesRel(unittest.TestCase):
 
         db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_get_highest_compose_id(self):
         compose_id = Compose.get_highest_compose_id(db.session)
         self.assertEqual(compose_id, 4)
@@ -351,20 +324,9 @@ class TestArtifactBuildComposesRel(unittest.TestCase):
                 sorted([rel.build.id for rel in compose.builds]))
 
 
-class TestEventDependency(unittest.TestCase):
+class TestEventDependency(helpers.ModelsTestCase):
     """Test Event.add_event_dependency"""
 
-    def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_event_dependencies(self):
         event = Event.create(db.session, "test_msg_id", "test", events.TestingEvent)
         db.session.commit()
diff --git a/tests/test_odcs_compose_state_change.py b/tests/test_odcs_compose_state_change.py
index 59c9430..b5527e7 100644
--- a/tests/test_odcs_compose_state_change.py
+++ b/tests/test_odcs_compose_state_change.py
@@ -22,7 +22,6 @@
 # Written by Chenxiong Qi <cqi@redhat.com>
 
 import six
-import unittest
 
 from mock import patch, PropertyMock
 
@@ -35,16 +34,14 @@ from freshmaker.models import (
 from freshmaker.events import ErrataAdvisoryRPMsSignedEvent
 from freshmaker.handlers.odcs import ComposeStateChangeHandler
 from freshmaker.events import ODCSComposeStateChangeEvent
+from tests import helpers
 
 
-class TestComposeStateChangeHandler(unittest.TestCase):
+class TestComposeStateChangeHandler(helpers.ModelsTestCase):
     """Test ODCSComposeStateChangeHandler"""
 
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestComposeStateChangeHandler, self).setUp()
 
         # Test data
         # (Inner build depends on outer build)
@@ -98,11 +95,6 @@ class TestComposeStateChangeHandler(unittest.TestCase):
                 build_id=build.id, compose_id=compose.id))
         db.session.commit()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     def test_cannot_handle_if_compose_is_not_done(self):
         event = ODCSComposeStateChangeEvent(
             'msg-id', {'id': 1, 'state': 'generating'}
diff --git a/tests/test_odcsclient.py b/tests/test_odcsclient.py
index 5293c10..1dab9af 100644
--- a/tests/test_odcsclient.py
+++ b/tests/test_odcsclient.py
@@ -22,16 +22,16 @@
 # Written by Chenxiong Qi <cqi@redhat.com>
 
 import six
-import unittest
 
 from mock import patch
 from odcs.client.odcs import AuthMech
 
 from freshmaker import conf
 from freshmaker.odcsclient import create_odcs_client
+from tests import helpers
 
 
-class TestCreateODCSClient(unittest.TestCase):
+class TestCreateODCSClient(helpers.FreshmakerTestCase):
     """Test odcsclient.create_odcs_client"""
 
     @patch.object(conf, 'odcs_auth_mech', new='kerberos')
diff --git a/tests/test_pulp.py b/tests/test_pulp.py
index b5e1b13..0332c45 100644
--- a/tests/test_pulp.py
+++ b/tests/test_pulp.py
@@ -22,17 +22,18 @@
 # Written by Chenxiong Qi <cqi@redhat.com>
 
 import json
-import unittest
 
 from mock import patch
 
 from freshmaker.pulp import Pulp
+from tests import helpers
 
 
-class TestPulp(unittest.TestCase):
+class TestPulp(helpers.FreshmakerTestCase):
     """Test interface to Pulp"""
 
     def setUp(self):
+        super(TestPulp, self).setUp()
         self.server_url = 'http://localhost/'
         self.username = 'qa'
         self.password = 'qa'
diff --git a/tests/test_views.py b/tests/test_views.py
index 6f164df..b258f74 100644
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -30,6 +30,7 @@ from mock import patch
 from freshmaker import app, db, events, models, login_manager
 from freshmaker.types import ArtifactType, ArtifactBuildState, EventState
 import freshmaker.auth
+from tests import helpers
 
 
 @login_manager.user_loader
@@ -37,13 +38,9 @@ def user_loader(username):
     return models.User.find_user_by_name(username=username)
 
 
-class ViewBaseTest(unittest.TestCase):
+class ViewBaseTest(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(ViewBaseTest, self).setUp()
         patched_allowed_clients = {'groups': ['freshmaker-clients'],
                                    'users': ['dev']}
         patched_admins = {'groups': ['admin'], 'users': ['root']}
@@ -66,9 +63,7 @@ class ViewBaseTest(unittest.TestCase):
         self.setup_test_data()
 
     def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
+        super(ViewBaseTest, self).tearDown()
 
         self.patch_allowed_clients.stop()
         self.patch_admins.stop()
@@ -116,13 +111,9 @@ class ViewBaseTest(unittest.TestCase):
         """Set up data for running tests"""
 
 
-class TestViews(unittest.TestCase):
+class TestViews(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(TestViews, self).setUp()
         self._init_data()
 
         self.client = app.test_client()
@@ -360,12 +351,9 @@ class TestViews(unittest.TestCase):
         self.assertEqual(data['message'], 'No such build state found.')
 
 
-class TestViewsMultipleFilterValues(unittest.TestCase):
+class TestViewsMultipleFilterValues(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
+        super(TestViewsMultipleFilterValues, self).setUp()
 
         self._init_data()
 
@@ -405,20 +393,11 @@ class TestViewsMultipleFilterValues(unittest.TestCase):
         self.assertEqual(len(evs), 2)
 
 
-class TestManualTriggerRebuild(unittest.TestCase):
+class TestManualTriggerRebuild(helpers.ModelsTestCase):
     def setUp(self):
-        db.session.remove()
-        db.drop_all()
-        db.create_all()
-        db.session.commit()
-
+        super(TestManualTriggerRebuild, self).setUp()
         self.client = app.test_client()
 
-    def tearDown(self):
-        db.session.remove()
-        db.drop_all()
-        db.session.commit()
-
     @patch('freshmaker.messaging.publish')
     @patch('freshmaker.views.Errata')
     def test_manual_rebuild(self, Errata, publish):

