Esempio n. 1
0
 def setUp(self):
     self.hello_world = HelloWorld(Resource)
     self.endpoints = Endpoints(Resource)
     self.model = Models(Resource)
     self.props = Props(Resource)
     self.run = RunModel(Resource)
     self.models = get_models(indra_dir)
Esempio n. 2
0
 def setUp(self):
     # none of the object's members names should have caps!
     self.hello_world = HelloWorld(Resource)
     self.endpoints = Endpoints(Resource)
     self.model = Models(Resource)
     self.props = Props(Resource)
     self.model_menu = ModelMenu(Resource)
     self.run = RunModel(Resource)
     self.models = load_models(indra_dir)
 def setUp(self):
     self.hello_world = HelloWorld(Resource)
     self.endpoints = Endpoints(Resource)
     self.model = Models(Resource)
     self.props = Props(Resource)
     self.model_menu = ModelMenu(Resource)
     self.run = RunModel(Resource)
     self.models = load_models(indra_dir)
     self.execution_key = self.props.get(13).get("execution_key").get("val")
Esempio n. 4
0
class Test(TestCase):
    def setUp(self):
        # none of the object's members names should have caps!
        self.hello_world = HelloWorld(Resource)
        self.endpoints = Endpoints(Resource)
        self.model = Models(Resource)
        self.props = Props(Resource)
        self.model_menu = ModelMenu(Resource)
        self.run = RunModel(Resource)
        self.models = load_models(indra_dir)

    def test_load_models(self):
        """
        See if models can be loaded.
        """
        rv = self.models
        test_model_file = indra_dir + "/models/models.json"
        with open(test_model_file) as file:
            test_rv = json.loads(file.read())["models_database"]
        self.assertEqual(rv, test_rv)

    def test_hello_world(self):
        """
        See if HelloWorld works.
        """
        rv = self.hello_world.get()
        self.assertEqual(rv, {'hello': 'world'})

    def test_endpoints(self):
        '''
        Check that /endpoints lists these endpoints.
        '''
        endpoints = set(self.endpoints.get()["Available endpoints"])
        test_endpoints = [
            "/endpoints", "/hello", "/model_creator", "/models",
            "/models/menu/", "/models/menu/run/<int:run_time>",
            "/models/props/<int:model_id>"
        ]
        for test_endpoint in test_endpoints:
            # While we could just convert test_endpoints into a set and then
            # check for set equality, this allows the output to show which
            # endpoint was missing.
            with self.subTest(test_endpoint=test_endpoint):
                self.assertIn(test_endpoint, endpoints)

    @skip("The test_put_model_creator() must be completely re-written.")
    def test_put_model_creator(self):
        '''
        Test the model creator API.
        This test is not good: first of all, it's about 20 tests packed into 1.
        Secondly, it is way too specifically tied to the details of
        the return.
        '''
        model_name = random_name()
        env_width = random.randrange(1000)
        env_height = random.randrange(1000)
        groups = []
        for _ in range(random.randrange(100)):
            groups.append({
                "group_name": random_name(),
                "num_of_agents": random.randrange(100),
                "color": "",
                "group_actions": []
            })
            # There's no point in testing color and group_actions because
            # APIServer.model_creator_api.CreateGroups.put doesn't do anything
            # with them anyway.
        model_features = {
            "model_name": model_name,
            "env_width": env_width,
            "env_height": env_height,
            "groups": groups
        }
        rv = put_model_creator(model_features)
        self.assertEqual(rv["type"], "env")
        self.assertEqual(model_name, rv["name"])
        self.assertEqual(model_name, rv["plot_title"])
        self.assertEqual(env_width, rv["width"])
        self.assertEqual(env_height, rv["height"])
        rv_members = rv["members"]
        for group in groups:
            group_name = group["group_name"]
            self.assertIn(group_name, rv_members)
            composite = rv_members[group_name]
            self.assertEqual(composite["type"], "composite")
            self.assertEqual(group_name, composite["name"])
            self.assertIn(model_name, composite["groups"])
            composite_members = composite["members"]
            for agent_index in range(group["num_of_agents"] - 1):
                agent_name = group_name + "_agent" + str(agent_index + 1)
                self.assertIn(agent_name, composite_members)
                agent = composite_members[agent_name]
                self.assertEqual(agent["type"], "agent")
                self.assertEqual(agent_name, agent["name"])
                self.assertIn(group_name, agent["groups"])
                self.assertEqual(model_name, agent["locator"])

    def test_get_model(self):
        """
        See if we can get models.
        """
        rv = self.model.get()

        test_model_file = indra_dir + "/models/models.json"
        with open(test_model_file) as file:
            test_models_db = json.loads(file.read())["models_database"]

        test_models_response = []
        for model in test_models_db:
            doc = ""
            if "doc" in model:
                doc = model["doc"]
            test_models_response.append({
                "model ID": model["model ID"],
                "name": model["name"],
                "doc": doc,
                "source": model["source"],
                "graph": model["graph"]
            })

        self.assertEqual(rv, test_models_response)

    @skip("Skipping get props.")
    def test_get_props(self):
        """
        See if we can get props.
        """
        model_id = random.randint(0, 10)
        rv = self.props.get(model_id)

        test_model_file = indra_dir + "/models/models.json"
        with open(test_model_file) as file:
            test_models_db = json.loads(file.read())["models_database"]

        with open(indra_dir + "/" + test_models_db[model_id]["props"]) as file:
            test_props = json.loads(file.read())

        self.assertEqual(rv, test_props)

    @skip("Skipping put props while json format is in flux.")
    def test_put_props(self):
        """
        Test whether we are able to put props
        """
        model_id = random.randint(0, 10)
        with app.test_request_context():
            rv = self.props.put(model_id)
        self.assertEqual(type(rv), dict)

    def test_get_ModelMenu(self):
        """
        Testing whether we are getting the menu.
        """
        rv = self.model_menu.get()
        test_menu_file = indra_dir + "/indra/menu.json"
        with open(test_menu_file) as file:
            test_menu = json.loads(file.read())["menu_database"]
        self.assertEqual(rv, test_menu)

    def test_err_return(self):
        """
        Testing whether we are able to get the right error message
        """
        rv = err_return("error message")
        self.assertEqual(rv, {"Error:": "error message"})
Esempio n. 5
0
class Test(TestCase):
    def setUp(self):
        self.hello_world = HelloWorld(Resource)
        self.endpoints = Endpoints(Resource)
        self.model = Models(Resource)
        self.props = Props(Resource)
        self.run = RunModel(Resource)
        self.models = get_models(indra_dir)

    def test_hello_world(self):
        """
        See if HelloWorld works.
        """
        rv = self.hello_world.get()
        self.assertEqual(rv, {'hello': 'world'})

    def test_endpoints(self):
        '''
        Check that /endpoints lists these endpoints.
        '''
        endpoints = self.endpoints.get()["Available endpoints"]
        self.assertGreaterEqual(len(endpoints), MIN_NUM_ENDPOINTS)

    def test_get_models(self):
        """
        See if we can get models.
        """
        with app.test_request_context():
            api_ret = self.model.get()
        for model in api_ret:
            self.assertIn(MODEL_ID, model)

    def test_get_props(self):
        """
        See if we can get props. Doing this for basic right now.
        Cannot seem to resolve props from model_id or name
        """
        model_id = 0
        rv = self.props.get(model_id)

        with open(
                os.path.join(indra_dir, "models", "props",
                             "basic.props.json")) as file:
            test_props = json.loads(file.read())

        self.assertTrue("exec_key" in rv)
        self.assertTrue(rv["exec_key"] is not None)
        # since exec_key is dynamically added to props the returned value
        # contains one extra key compared to the test_props loaded from file
        del rv["exec_key"]
        self.assertEqual(rv, test_props)

    def test_put_props(self):
        """
        Test whether we are able to put props and get back a model.
        This test should be re-written from scratch.
        """
        pass

    def test_model_run(self):
        model_id = 0
        props = self.props.get(model_id)
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            rv = client.put('/models/props/' + str(model_id),
                            data=json.dumps(props))
        self.assertEqual(rv._status_code, 200)
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            response = client.put('/models/run/' + str(10),
                                  data=json.dumps(rv.json))

        self.assertEqual(response._status_code, 200)
        self.assertNotEqual(
            rv.json.get('env').get('locations'),
            response.json.get('env').get('locations'))

    '''
    def test_get_ModelMenu(self):
        """
        Testing whether we are getting the menu.
        """
        rv = self.model_menu.get()
        test_menu_file = indra_dir + "/lib/menu.json"
        with open(test_menu_file) as file:
            test_menu = json.loads(file.read())["menu_database"]
        self.assertEqual(rv, test_menu)
    '''

    def test_err_return(self):
        """
        Testing whether we are able to get the right error message
        """
        rv = err_return("error message")
        self.assertEqual(rv, {"Error:": "error message"})
 def setUp(self):
     self.hello_world = HelloWorld(Resource)
     self.endpoints = Endpoints(Resource)
     self.pophist = epts.PopHist(Resource)
     self.props = Props(Resource)
     self.run = RunModel(Resource)
class TestAPI(TestCase):
    def setUp(self):
        self.hello_world = HelloWorld(Resource)
        self.endpoints = Endpoints(Resource)
        self.pophist = epts.PopHist(Resource)
        self.props = Props(Resource)
        self.run = RunModel(Resource)

    def test_hello_world(self):
        """
        See if HelloWorld works.
        """
        rv = self.hello_world.get()
        self.assertEqual(rv, {'hello': 'world'})

    def test_endpoints(self):
        '''
        Check that /endpoints lists these endpoints.
        '''
        endpoints = self.endpoints.get()["Available endpoints"]
        self.assertGreaterEqual(len(endpoints), MIN_NUM_ENDPOINTS)

    def test_get_model_menu(self):
        mfm = epts.MenuForModel(Resource)
        self.assertTrue(isinstance(mfm.get(), dict))

    def test_get_models(self):
        """
        See if we can get models.
        """
        models = Models(Resource)
        with app.test_request_context():
            api_ret = models.get()
        for model in api_ret:
            self.assertIn(MODEL_ID, model)

    def test_user_msgs(self):
        """
        Test getting user messages.
        """
        um = epts.UserMsgs(Resource)
        self.assertTrue(isinstance(um.get(BASIC_ID), str))

    def test_get_pophist(self):
        """
        Test getting pophist.
        A rule: the number of periods must be one less than
        the length of each pop list. (Because we record pops for
        period zero.
        """
        with app.test_request_context():
            pophist = self.pophist.get(0)
        self.assertTrue(isinstance(pophist, dict))
        self.assertIn(epts.POPS, pophist)
        self.assertIn(epts.PERIODS, pophist)
        for grp in pophist[epts.POPS]:
            self.assertEqual(len(pophist[epts.POPS][grp]),
                             pophist[epts.PERIODS] + 1)

    @skip("problem with restoring props.")
    def test_get_props(self):
        """
        See if we can get props. Doing this for basic right now.
        Cannot seem to resolve props from model_id or name
        """
        model_id = BASIC_ID
        props = self.props.get(model_id)

        with open(
                os.path.join(indra_dir, "models", "props",
                             "basic.props.json")) as file:
            test_props = json.loads(file.read())

        self.assertTrue("exec_key" in props)
        self.assertTrue(props["exec_key"] is not None)
        # since exec_key is dynamically added to props the returned value
        # contains one extra key compared to the test_props loaded from file
        del props["exec_key"]
        self.assertEqual(props, test_props)

    def test_put_props(self):
        """
        Test whether we are able to put props and get back a model.
        This test should be re-written from scratch.
        """
        pass

    @skip("problem with restoring props.")
    def test_model_run(self):
        """
        This is going to see if we can run a model.
        """
        model_id = BASIC_ID
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            model_before_run = client.get(f'{epts.MODELS_URL}/{BASIC_ID}')
        self.assertEqual(model_before_run._status_code, epts.HTTP_SUCCESS)
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            model_after_run = client.put(f'{epts.MODEL_RUN_URL}/{TEST_TURNS}',
                                         data=json.dumps(
                                             model_before_run.json))

        self.assertEqual(model_after_run._status_code, epts.HTTP_SUCCESS)
        # if the model really ran, the old period must be less than the new
        # period.
        self.assertLess(model_before_run.json.get('period'),
                        model_after_run.json.get('period'))

    def test_err_return(self):
        """
        Testing whether we are able to get the right error message
        """
        rv = err_return("error message")
        self.assertEqual(rv, {"Error:": "error message"})

    def test_no_model_found_for_name(self):
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            response = client.post(f'{epts.MODELS_URL}/1',
                                   data=json.dumps(({
                                       'model_name': "random"
                                   })))
        self.assertEqual(response._status_code, 404)

    def test_model_created_for_testing_with_incorrect_id(self):
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            response = client.post(f'{epts.MODELS_URL}/250',
                                   data=json.dumps({}))

        self.assertEqual(response._status_code, epts.HTTP_NOT_FOUND)

    def test_create_test_model_without_id(self):
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            response = client.post(f'{epts.MODELS_URL}/{TEST_MODEL_ID}',
                                   data=json.dumps(({
                                       'model_name': "Basic"
                                   })))
            self.assertEqual(response._status_code, epts.HTTP_SUCCESS)
            model = response.json
            self.assertEqual(model['exec_key'], TEST_MODEL_ID)

    @skip("Problem with saved registries.")
    def test_model_run_after_test_model_created(self):
        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            response = client.post(f'{epts.MODELS_URL}/{TEST_MODEL_ID}',
                                   data=json.dumps(({
                                       'model_name': "Basic"
                                   })))
            self.assertEqual(response._status_code, epts.HTTP_SUCCESS)
            model = response.json

        with app.test_client() as client:
            client.environ_base['CONTENT_TYPE'] = 'application/json'
            model_after_run = client.put(f'{epts.MODEL_RUN_URL}/{TEST_TURNS}',
                                         data=json.dumps(model))

        self.assertEqual(model_after_run._status_code, epts.HTTP_SUCCESS)
        self.assertLess(model.get('period'),
                        model_after_run.json.get('period'))
class Test(TestCase):
    def setUp(self):
        self.hello_world = HelloWorld(Resource)
        self.endpoints = Endpoints(Resource)
        self.model = Models(Resource)
        self.props = Props(Resource)
        self.model_menu = ModelMenu(Resource)
        self.run = RunModel(Resource)
        self.models = load_models(indra_dir)
        self.execution_key = self.props.get(13).get("execution_key").get("val")

    def test_load_models(self):
        """
        See if models can be loaded.
        """
        rv = self.models
        test_model_file = indra_dir + MODEL_FILE
        with open(test_model_file) as file:
            test_rv = json.loads(file.read())["models_database"]
        self.assertEqual(rv, test_rv)

    def test_hello_world(self):
        """
        See if HelloWorld works.
        """
        rv = self.hello_world.get()
        self.assertEqual(rv, {'hello': 'world'})

    def test_endpoints(self):
        '''
        Check that /endpoints lists these endpoints.
        '''
        endpoints = self.endpoints.get()["Available endpoints"]
        self.assertGreaterEqual(len(endpoints), MIN_NUM_ENDPOINTS)

    def test_get_models(self):
        """
        See if we can get models.
        """
        api_ret = self.model.get()
        for model in api_ret:
            self.assertIn(MODEL_ID, model)

    @skip("Skipping get props.")
    def test_get_props(self):
        """
        See if we can get props.
        """
        model_id = random.randint(0, 10)
        rv = self.props.get(model_id)

        test_model_file = indra_dir + MODEL_FILE
        with open(test_model_file) as file:
            test_models_db = json.loads(file.read())["models_database"]

        with open(indra_dir + "/" + test_models_db[model_id]["props"]) as file:
            test_props = json.loads(file.read())

        self.assertEqual(rv, test_props)

    @skip("Skipping put props while json format is in flux.")
    def test_put_props(self):
        """
        Test whether we are able to put props
        """
        model_id = random.randint(0, 10)
        with app.test_request_context():
            rv = self.props.put(model_id)
        self.assertEqual(type(rv), dict)

    def test_get_ModelMenu(self):
        """
        Testing whether we are getting the menu.
        """
        rv = self.model_menu.get(execution_id=self.execution_key)
        test_menu_file = indra_dir + "/indra/menu.json"
        with open(test_menu_file) as file:
            test_menu = json.loads(file.read())["menu_database"]
        self.assertEqual(rv, test_menu)

    def test_err_return(self):
        """
        Testing whether we are able to get the right error message
        """
        rv = err_return("error message")
        self.assertEqual(rv, {"Error:": "error message"})