Skip to content

Instantly share code, notes, and snippets.

@apast
Last active August 15, 2018 10:38
Show Gist options
  • Save apast/23a896db5915229bb114731e82631be6 to your computer and use it in GitHub Desktop.
Save apast/23a896db5915229bb114731e82631be6 to your computer and use it in GitHub Desktop.
Set and Get keys to and from a database
from tornado import web
from tornado.ioloop import IOLoop
class SetGetDB(web.RequestHandler):
def initialize(self, db):
self.db = db
def post(self):
args = self.request.query_arguments
elements = {k: v[0].decode() for k, v in args.items()}
self.db.update(elements)
self.set_status(201)
self.finish()
def get(self):
key = self.get_argument("key")
if key in self.db:
self.set_status(200)
self.write(self.db[key])
else:
self.set_status(404)
self.finish()
def build_app():
db = {}
application = web.Application([
("/set", SetGetDB, dict(db=db)),
("/get", SetGetDB, dict(db=db)),
])
return application
def run(port=4000):
application = build_app()
application.listen(port)
IOLoop.current().start()
if __name__ == "__main__":
run()
import pytest
from tornado.httputil import url_concat
from tornado.httpclient import HTTPError
from setgetdb import build_app
@pytest.fixture
def app():
return build_app()
@pytest.mark.gen_test
def test_set_valid_value(http_client, base_url):
post_url = url_concat(base_url+"/set", dict(k="v"))
response = yield http_client.fetch(post_url, method="POST", body="")
assert response.code == 201
get_url = url_concat(base_url+"/get", dict(key="k"))
response_get = yield http_client.fetch(get_url)
assert response_get.code == 200
assert response_get.body.decode() == "v"
@pytest.mark.gen_test
def test_get_inexistent_key_should_return_not_found(http_client, base_url):
get_url = url_concat(base_url+"/get", dict(key="_inexistent_key_"))
with pytest.raises(HTTPError) as error:
yield http_client.fetch(get_url)
assert error.match(r"^HTTP 404.*")
@pytest.mark.gen_test
def test_rewrite_value_updates_to_new_value(http_client, base_url):
post_url_1 = url_concat(base_url+"/set", dict(k="1"))
yield http_client.fetch(post_url_1, method="POST", body="")
get_url_1 = url_concat(base_url+"/get", dict(key="k"))
response_get_1 = yield http_client.fetch(get_url_1)
assert response_get_1.body.decode() == "1"
post_url_2 = url_concat(base_url+"/set", dict(k="2"))
yield http_client.fetch(post_url_2, method="POST", body="")
get_url_2 = url_concat(base_url+"/get", dict(key="k"))
response_get_2 = yield http_client.fetch(get_url_2)
assert response_get_2.body.decode() == "2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment