Skip to content

Instantly share code, notes, and snippets.

@vlna
Created December 9, 2020 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlna/7d839442362eff8a346082ccd9b177f5 to your computer and use it in GitHub Desktop.
Save vlna/7d839442362eff8a346082ccd9b177f5 to your computer and use it in GitHub Desktop.
How to mock exception in method
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