Reputation: 21168
I need to mock requests
library, so figured to use requests_mock
library for that. Though I wonder how can I create a fixture for my test class when using unittest
library?
I can do this with testtools
, like:
import testtools
from requests_mock.contrib import fixture
class MyTestCase(testtools.TestCase):
TEST_URL = 'http://some-not-existing-url.com'
def setUp(self):
super().setUp()
self.requests_mock = self.useFixture(fixture.Fixture())
self.requests_mock.post(self.TEST_URL, status_code='200')
def test_01_method(self):
resp = requests.post(self.TEST_URL)
self.assertEqual('200', resp.status_code)
Now unittest
does not have useFixture
method. Is there some equivalent in unittest
lib? Or I need to use some different approach there?
Trying similar thing (without useFixture
, crashes tests):
import unittest
from requests_mock.contrib import fixture
class MyTestCase(unittest.TestCase):
TEST_URL = 'http://some-not-existing-url.com'
def setUp(self):
super().setUp()
self.requests_mock = fixture.Fixture()
self.requests_mock.post(self.TEST_URL, status_code='200')
def test_01_method(self):
resp = requests.post(self.TEST_URL)
self.assertEqual('200', resp.status_code)
Running with unittest
, I get [Errno -2] Name or service not known
, which clearly shows that mocking does not apply correctly.
P.S. I need unittest
lib, because it is used in framework which I use. So I need to incorporate these unittests to align with that framework.
Upvotes: 1
Views: 931
Reputation: 436
Rather than using a fixture, you can explicitly start the mock in setUp
and stop it in tearDown
.
For example:
import unittest
import requests_mock
import requests
class MyTestCase(unittest.TestCase):
TEST_URL = 'http://some-not-existing-url.com'
def setUp(self):
super().setUp()
self.requests_mock = requests_mock.Mocker()
self.requests_mock.post(self.TEST_URL, status_code='200')
self.requests_mock.start()
def test_01_method(self):
resp = requests.post(self.TEST_URL)
self.assertEqual('200', resp.status_code)
def tearDown(self):
super().tearDown()
self.requests_mock.stop()
Upvotes: 4