我正在为经过身份验证的 RESTful API 编写 Python 包装器。我现在正在编写我的测试套件(也是这里的第一次测试编写者)但有几个问题:
1.a) 我如何拨打电话,但不必将凭据硬编码到测试中,因为我会将它扔到 Github 上?
1.b)我有点知道嘲笑,但不知道如何去做。这会让我不必调用实际的服务吗?解决此问题的最佳方法是什么?
2)我要测试什么 - 只需确保我的方法通过字典中的某些项目?
3)我应该在这里遵循的任何最佳实践?
我正在为经过身份验证的 RESTful API 编写 Python 包装器。我现在正在编写我的测试套件(也是这里的第一次测试编写者)但有几个问题:
1.a) 我如何拨打电话,但不必将凭据硬编码到测试中,因为我会将它扔到 Github 上?
1.b)我有点知道嘲笑,但不知道如何去做。这会让我不必调用实际的服务吗?解决此问题的最佳方法是什么?
2)我要测试什么 - 只需确保我的方法通过字典中的某些项目?
3)我应该在这里遵循的任何最佳实践?
Hey TJ if you can show me an example of one function that you are writing (code under test, not the test code) then I can give you an example test.
Generally though:
1.a You would mock the call to the external api, you are not trying to test whether their authentication mechanism, or your internet connection is working. You are just trying to test that you are calling their api with the correct signature.
1.b Mocking in Python is relatively straight forward. I generally use the mocking library written by Michael Foord. pip install mock
will get you started. Then you can do things like
import unittest
from mock import call, patch
from my_module import wrapper_func
class ExternalApiTest(unittest.TestCase):
@patch('my_module.api_func')
def test_external_api_call(self, mocked_api_func):
response = wrapper_func('user', 'pass')
self.assertTrue(mocked_api_func.called)
self.assertEqual(
mocked_api_func.call_args_list,
[call('user', 'pass')]
)
self.assertEqual(mocked_api_func.return_value, response)
In this example we are replacing the api_func
inside my_module
with a mock object. The mock object records what has been done to it. It's important to remember where to patch. You don't patch the location you imported the object from. You patch it in the location that you will be using it.
You test that your code is doing the correct thing with a given input. Testing pure functions (pure in the functional programming sense) is pretty simple. You assert that given a input a, this function returns output b. It gets a bit trickier when your functions have lots of side effects.
If you are finding it too hard or complicated to test a certain functiob/method it can mean that it's a badly written piece of code. Try breaking it up into testable chunks and rather than passing objects into functions try to pass primitives where possible.