-
Corné Lukken authored
These lofar_git tests use different test methodologies to serve as a guide for developers new to unittests in Python.
Corné Lukken authoredThese lofar_git tests use different test methodologies to serve as a guide for developers new to unittests in Python.
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
test_lofar_git.py 3.03 KiB
# -*- coding: utf-8 -*-
#
# This file is part of the LOFAR 2.0 Station Software
#
#
#
# Distributed under the terms of the APACHE license.
# See LICENSE.txt for more info.
import git
from unittest import mock
from util import lofar_git
from test import base
class TestLofarGit(base.TestCase):
def setUp(self):
super(TestLofarGit, self).setUp()
# Clear the cache as this function of lofar_git uses LRU decorator
# This is a good demonstration of how unit tests in Python can have
# permanent effects, typically fixtures are needed to restore these.
lofar_git.get_version.cache_clear()
def test_get_version(self):
"""Test if attributes of get_repo are correctly used by get_version"""
with mock.patch.object(lofar_git, 'get_repo') as m_get_repo:
m_commit = mock.Mock()
m_commit.return_value = "123456"
m_is_dirty = mock.Mock()
m_is_dirty.return_value = True
m_get_repo.return_value = mock.Mock(
active_branch="main", commit=m_commit, tags=[],
is_dirty=m_is_dirty)
# No need for special string equal in Python
self.assertEqual("*main [123456]", lofar_git.get_version())
def test_get_version_tag(self):
"""Test if get_version determines production_ready for tagged commit"""
with mock.patch.object(lofar_git, 'get_repo') as m_get_repo:
m_commit = mock.Mock()
m_commit.return_value = "123456"
m_is_dirty = mock.Mock()
m_is_dirty.return_value = False
m_tag = mock.Mock(commit="123456")
m_tag.__str__ = mock.Mock(return_value= "version-1.2")
m_get_repo.return_value = mock.Mock(
active_branch="main", commit=m_commit,
tags=[m_tag], is_dirty=m_is_dirty)
self.assertEqual("version-1.2", lofar_git.get_version())
@mock.patch.object(lofar_git, 'get_repo')
def test_get_version_tag_dirty(self, m_get_repo):
"""Test if get_version determines dirty tagged commit"""
m_commit = mock.Mock()
m_commit.return_value = "123456"
m_is_dirty = mock.Mock()
m_is_dirty.return_value = False
m_tag = mock.Mock(commit="123456")
m_tag.__str__ = mock.Mock(return_value= "version-1.2")
# Now m_get_repo is mocked using a decorator
m_get_repo.return_value = mock.Mock(
active_branch="main", commit=m_commit,
tags=[m_tag], is_dirty=m_is_dirty)
self.assertEqual("version-1.2", lofar_git.get_version())
def test_catch_repo_error(self):
"""Test if invalid git directories will raise error"""
with mock.patch.object(lofar_git, 'get_repo') as m_get_repo:
# Configure lofar_git.get_repo to raise InvalidGitRepositoryError
m_get_repo.side_effect = git.InvalidGitRepositoryError
# Test that error is raised by get_version
self.assertRaises(
git.InvalidGitRepositoryError, lofar_git.get_version)