def post(self): """ Register a new host """ hostname = self.get_argument(Parameter.HOSTNAME) host_id = self.get_argument(Parameter.HOST_ID) host_added = self._args.storage.add_host(Host(host_id, hostname)) if not host_added: self.set_status(400)
def _try_create(self, config: dict): name = config[Attribute.NAME] id_ = config[Attribute.ID] if not self._storage.host_exists(id_): self._storage.add_host(Host( id_, name )) log.debug("Added '{type}': {name}".format(type=ConfigurationType.HOST, name=name))
def test_get_nonexisting_host(self): nonexisting_host = Host("", "") self._set_logged_in_user(admin_user) self._host_storage.set_response_data_for("get_host_by_id", value=nonexisting_host) url = tornado.httputil.url_concat(self.API_ENDPOINT, {Parameter.HOST_ID: "1234-5678"}) response = self.fetch(url, method="GET") decoded_response = tornado.escape.json_decode(response.body) self.assertIn("hosts", decoded_response) self.assertEqual(len(decoded_response["hosts"]), 0, "Expects to return an empty list of all hosts")
def test_get_all_hosts(self): storage = JsonFormattedHostStorage(self._storage) storage.add_host(valid_host) storage.add_host(Host(id_="2345-6789", name="another-host")) all_hosts = storage.get_all_hosts() self.assertEqual(len(all_hosts), 2)
def test_add_existing_host(self): storage = JsonFormattedHostStorage(self._storage) storage.add_host(Host(id_="1234-5678", name="another-host")) # id is the unique constraint self.assertFalse(storage.add_host(valid_host)) self._storage.write.assert_called_once()
import unittest from unittest.mock import ( Mock, call, ANY ) from application import Host from application.storage import ( NonExistingHost, IOStorage ) from .hosts import JsonFormattedHostStorage valid_host = Host(id_="1234-5678", name="hostname") class TestJsonFormattedHostStorage(unittest.TestCase): def __init__(self, *args): super().__init__(*args) self._storage = Mock(spec=IOStorage) def setUp(self): self._reset_mock() def _reset_mock(self): self._storage.reset_mock() self._storage.read.return_value = "[]" def test_load_on_init(self): storage = JsonFormattedHostStorage(self._storage)
from application.storage import HostStorage from application import Host from ..response_mixin import StubResponseMixin stored_host = Host("1234-5678", "hostname") class HostStorageStub(HostStorage, StubResponseMixin): def default_response_data(self) -> dict: response_data = { "add_host": True, "host_exists": False, "remove_host_by_id": True, "get_host_by_id": stored_host, "get_all_hosts": [stored_host] } return response_data def add_host(self, host: Host) -> bool: """Returns True if added successfully, False if item already exists""" return self.get_response() def host_exists(self, id_: str) -> bool: return self.get_response() def remove_host_by_id(self, id_: str) -> bool: """Returns True if is deleted successfully, False if item don't exists""" return self.get_response() def get_host_by_id(self, id_: str) -> Host: return self.get_response()