Reputation: 16819
I'm converting a code base from Ruby to Python. In Ruby/RSpec I wrote custom "matchers" which allow me to black-box test web services like this:
describe 'webapp.com' do
it 'is configured for ssl' do
expect('www.webapp.com').to have_a_valid_cert
end
end
I'd like to write code to extend a Python testing framework with the same functionality. I realize that it will probably not look the same, of course. It doesn't need to be BDD. "Assert..." is just fine. Is pytest
a good candidate for extending? Are there any examples of writing extensions like these?
Upvotes: 1
Views: 370
Reputation: 2372
Yes, pytest is good framework for doing what are you needs. We are using pytest with requests and PyHamcrest. Look at this example:
import pytest
import requests
from hamcrest import *
class SiteImpl:
def __init__(self, url):
self.url = url
def has_valid_cert(self):
return requests.get(self.url, verify=True)
@pytest.yield_fixture
def site(request):
# setUp
yield SiteImpl('https://' + request.param)
# tearDown
def has_status(item):
return has_property('status_code', item)
@pytest.mark.parametrize('site', ['google.com', 'github.com'], indirect=True)
def test_cert(site):
assert_that(site.has_valid_cert(), has_status(200))
if __name__ == '__main__':
pytest.main(args=[__file__, '-v'])
The code above uses parametrization for fixture site
. Also yeld_fixture
give you possibility to setUp and tearDown. Also you can write inline matcher has_status
, which can used for easy read test assert.
Upvotes: 1