Created
December 9, 2020 13:37
-
-
Save vlna/7d839442362eff8a346082ccd9b177f5 to your computer and use it in GitHub Desktop.
How to mock exception in method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gitlab | |
from gitlab.exceptions import GitlabError | |
class MainLogic(): | |
def open_gitlab(self): | |
try: | |
gl = gitlab.Gitlab('https://example.com', 'MyToken') | |
gl.auth() | |
log.error('Connected to GitLab.') | |
return gl | |
except GitlabError as e: | |
log.error('Wrong configuration and/or unable to connect GitLab.') | |
raise GitlabError from e | |
import logging | |
import unittest | |
from unittest import mock | |
log = logging.getLogger(__name__) | |
class MyTestCase(unittest.TestCase): | |
def test_open_gitlab_exception(self): | |
ml = MainLogic() | |
gitlab.Gitlab = mock.Mock() | |
#gitlab.Gitlab.auth = mock.Mock(side_effect=GitlabError('I need exception in open_gitlab')) | |
gitlab.Gitlab.auth.side_effect = GitlabError('I need exception in open_gitlab') | |
try: | |
gl = ml.open_gitlab() | |
except GitlabError: | |
print('OK') | |
assert True | |
else: | |
print('NOK') | |
assert False | |
mtc = MyTestCase() | |
mtc.test_open_gitlab_exception() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment