Exemple #1
0
def test_dtmult_post(test_flask_client):
    """Tests the POST method"""

    # Test arg parsing

    resp = test_flask_client.post(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST

    # Test multiplier check

    data = {"multiplier": -1}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.data.decode() == "Multiplier must be greater than 0"

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from set_sim_speed

        sim_proxy_mock.simulation.set_speed.return_value = "Couldn't set speed"

        data["multiplier"] = 10
        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't set speed"

        # Test valid response

        sim_proxy_mock.simulation.set_speed.return_value = None
        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.OK
Exemple #2
0
def test_step_post(test_flask_client):
    """Tests the POST method"""

    # Test agent mode check

    Settings.SIM_MODE = SimMode.Sandbox

    resp = test_flask_client.post(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.data.decode() == "Must be in agent mode to use step"

    with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from step

        sim_proxy_mock.simulation.step.return_value = "Error"

        Settings.SIM_MODE = SimMode.Agent

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Error"

        # Test valid response

        sim_proxy_mock.simulation.step.return_value = None

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.OK
Exemple #3
0
def test_op_post_agent_mode(test_flask_client):
    """Tests the POST endpoint"""

    # Test error when in agent mode

    settings.Settings.SIM_MODE = SimMode.Agent

    resp = test_flask_client.post(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.data.decode() == "Can't resume sim from mode Agent"

    with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from simulation resume

        sim_proxy_mock.simulation.resume.return_value = "Couldn't resume sim"

        settings.Settings.SIM_MODE = SimMode.Sandbox

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't resume sim"

        # Test valid response

        sim_proxy_mock.simulation.resume.return_value = None

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.OK
def test_pos_get_single(test_flask_client):
    """Tests the GET method with a single aircraft"""

    # Test arg parsing

    endpoint_str = f"{_ENDPOINT_PATH}?{utils.CALLSIGN_LABEL}"

    callsign = ""
    resp = test_flask_client.get(f"{endpoint_str}={callsign}")
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert utils.CALLSIGN_LABEL in resp.json["message"]

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        utils_patch.CALLSIGN_LABEL = utils.CALLSIGN_LABEL
        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from simulation properties

        sim_proxy_mock.simulation.properties = "Error"

        endpoint_str = f"{endpoint_str}=TEST"

        resp = test_flask_client.get(endpoint_str)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Error"

        # Test aircraft existence check

        sim_proxy_mock.simulation.properties = TEST_SIM_PROPS

        with api.FLASK_APP.test_request_context():
            utils_patch.check_exists.return_value = bad_request_resp(
                "Missing aircraft")

        resp = test_flask_client.get(endpoint_str)
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "Missing aircraft"

        # Test error from aircraft properties

        utils_patch.check_exists.return_value = None
        sim_proxy_mock.aircraft.properties.return_value = "Missing properties"

        resp = test_flask_client.get(endpoint_str)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Missing properties"

        # Test valid response

        sim_proxy_mock.aircraft.properties.return_value = TEST_AIRCRAFT_PROPS

        resp = test_flask_client.get(endpoint_str)
        assert resp.status_code == HTTPStatus.OK
        assert resp.json == {
            **utils.convert_aircraft_props(TEST_AIRCRAFT_PROPS),
            "scenario_time":
            TEST_SIM_PROPS.scenario_time,
        }
Exemple #5
0
def test_seed_post(test_flask_client):
    """Tests the POST method """

    # Test arg parsing

    resp = test_flask_client.post(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "value" in resp.json["message"]

    data = {"value": ""}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "value" in resp.json["message"]

    # Test seed range checking

    data = {"value": -1}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert (resp.data.decode(
    ) == "Invalid seed specified. Must be a positive integer less than 2^32")

    data = {"value": 2**32}  # Max value allowed by np.random.seed()
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert (resp.data.decode(
    ) == "Invalid seed specified. Must be a positive integer less than 2^32")

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from set_seed

        sim_proxy_mock.simulation.set_seed.return_value = "Error"

        data = {"value": 123}

        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Error"

        # Test valid response

        sim_proxy_mock.simulation.set_seed.return_value = None

        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.OK
Exemple #6
0
def test_hdg_post(test_flask_client):
    """Tests the POST method"""

    # Test arg parsing

    resp = test_flask_client.post(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST

    data = {api_utils.CALLSIGN_LABEL: "FAKE"}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST

    data["hdg"] = "aaa"
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST

    with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test aircraft exists check

        with api.FLASK_APP.test_request_context():
            utils_patch.check_exists.return_value = bad_request_resp(
                "Missing aircraft")

        data["hdg"] = 123

        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "Missing aircraft"

        # Test error from set_heading

        utils_patch.check_exists.return_value = None
        sim_proxy_mock.aircraft.set_heading.return_value = "Couldn't set heading"

        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't set heading"

        # Test valid response

        sim_proxy_mock.aircraft.set_heading.return_value = None

        resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
        assert resp.status_code == HTTPStatus.OK
Exemple #7
0
def test_siminfo_get(test_flask_client):
    """Tests the POST method"""

    with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from simulation properties

        sim_proxy_mock.simulation.properties = "Error"

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't get the sim properties: Error"

        # Test error from aircraft callsigns

        sim_proxy_mock.simulation.properties = TEST_SIM_PROPS
        sim_proxy_mock.aircraft.callsigns = "Error"

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't get the callsigns: Error"

        # Test valid response

        sim_proxy_mock.aircraft.callsigns = [Callsign("AAA"), Callsign("BBB")]

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.OK
        assert resp.json == {
            "callsigns": ["AAA", "BBB"],
            "mode": Settings.SIM_MODE.name,
            "sector_name": TEST_SIM_PROPS.sector_name,
            "scenario_name": TEST_SIM_PROPS.scenario_name,
            "scenario_time": 0,
            "seed": 0,
            "sim_type": "BlueSky",
            "speed": 1.0,
            "state": "INIT",
            "dt": TEST_SIM_PROPS.dt,
            "utc_datetime": str(TEST_SIM_PROPS.utc_datetime),
        }
Exemple #8
0
def test_shutdown_post(test_flask_client):
    """Tests the POST method"""

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error when no shutdown function available

        sim_proxy_mock.shutdown.return_value = False

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert (
            resp.data.decode()
            == "No shutdown function available. (Sim shutdown ok = False)"
        )

        # Test exception from shutdown method

        sim_proxy_mock.shutdown.return_value = True

        def throwy_mc_throwface():
            raise Exception("Error")

        resp = test_flask_client.post(
            _ENDPOINT_PATH,
            environ_base={"werkzeug.server.shutdown": throwy_mc_throwface},
        )
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert (
            resp.data.decode() == "Could not shutdown: Error. (Sim shutdown ok = True)"
        )

        # Test valid response

        resp = test_flask_client.post(
            _ENDPOINT_PATH, environ_base={"werkzeug.server.shutdown": lambda: None},
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp.data.decode() == "BlueBird shutting down! (Sim shutdown ok = True)"
Exemple #9
0
def test_reset_post(test_flask_client):
    """Tests the POST method"""

    with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from simulation reset

        sim_proxy_mock.simulation.reset.return_value = "Error"

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Error"

        sim_proxy_mock.simulation.reset.return_value = None

        resp = test_flask_client.post(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.OK
def test_pos_get_all(test_flask_client):
    """Tests the GET method with all aircraft"""

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        utils_patch.CALLSIGN_LABEL = utils.CALLSIGN_LABEL
        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test error from all_properties

        sim_proxy_mock.simulation.properties = TEST_SIM_PROPS
        sim_proxy_mock.aircraft.all_properties = "Error"

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode(
        ) == "Couldn't get the aircraft properties: Error"

        # Test error when no aircraft

        sim_proxy_mock.aircraft.all_properties = None

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "No aircraft in the simulation"

        # Test valid response

        sim_proxy_mock.aircraft.all_properties = {
            str(TEST_AIRCRAFT_PROPS.callsign): TEST_AIRCRAFT_PROPS,
        }

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.OK
        assert resp.json == {
            **utils.convert_aircraft_props(TEST_AIRCRAFT_PROPS),
            **{
                "scenario_time": TEST_SIM_PROPS.scenario_time
            },
        }
Exemple #11
0
def test_cre_post(test_flask_client):
    """Tests the POST method"""

    # Test arg parsing

    data = {}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert utils.CALLSIGN_LABEL in resp.json["message"]

    callsign = "T"
    data = {utils.CALLSIGN_LABEL: callsign}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert utils.CALLSIGN_LABEL in resp.json["message"]

    callsign = "AAA"
    data = {utils.CALLSIGN_LABEL: callsign}
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "type" in resp.json["message"]

    data["type"] = ""
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "lat" in resp.json["message"]

    data["lat"] = 91
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "lon" in resp.json["message"]

    data["lon"] = 181
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "hdg" in resp.json["message"]

    data["hdg"] = "aaa"
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.json["message"]["hdg"] == "Heading must be an int"

    data["hdg"] = 123
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "alt" in resp.json["message"]

    data["alt"] = -1
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.json["message"]["alt"] == "Altitude must be positive"

    data["alt"] = "FL100"
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert "gspd" in resp.json["message"]

    data["gspd"] = "..."
    resp = test_flask_client.post(_ENDPOINT_PATH, json=data)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.json["message"]["gspd"] == "Ground speed must be numeric"

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        utils_patch.CALLSIGN_LABEL = utils.CALLSIGN_LABEL

        # Test response when aircraft exists

        with api.FLASK_APP.test_request_context():
            response = responses.bad_request_resp("Missing aircraft")

        utils_patch.check_exists.return_value = response

        data = {
            utils.CALLSIGN_LABEL: "TEST1",
            "type": "",
            "lat": "1.23",
            "lon": "4.56",
            "hdg": 123,
            "alt": 18_500,
            "gspd": 50,
        }
Exemple #12
0
def test_listroute_get(test_flask_client):
    """Tests the GET method"""

    endpoint_path = f"{_ENDPOINT_PATH}?{utils.CALLSIGN_LABEL}="

    # Test arg parsing

    resp = test_flask_client.get(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST

    callsign_str = "A"
    resp = test_flask_client.get(f"{endpoint_path}{callsign_str}")
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert utils.CALLSIGN_LABEL in resp.json["message"]

    with mock.patch(patch_utils_path(_ENDPOINT), wraps=utils) as utils_patch:

        utils_patch.CALLSIGN_LABEL = utils.CALLSIGN_LABEL
        sim_proxy_mock = mock.Mock()
        utils_patch.sim_proxy.return_value = sim_proxy_mock

        # Test aircraft exists check

        with api.FLASK_APP.test_request_context():
            utils_patch.check_exists.return_value = bad_request_resp(
                "Missing aircraft")

        callsign_str = "TEST"
        resp = test_flask_client.get(f"{endpoint_path}{callsign_str}")
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "Missing aircraft"

        # Test response when no route defined

        utils_patch.check_exists.return_value = None
        sim_proxy_mock.aircraft.route.return_value = "Aircraft has no route"

        resp = test_flask_client.get(f"{endpoint_path}{callsign_str}")
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "Aircraft has no route"

        # Test error from aircraft route

        sim_proxy_mock.aircraft.route.return_value = "Couldn't get route"

        resp = test_flask_client.get(f"{endpoint_path}{callsign_str}")
        assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
        assert resp.data.decode() == "Couldn't get route"

        # Test valid response

        route_info = (
            "test_route",
            "FIRE",
            ["WATER", "FIRE", "EARTH"],
        )
        sim_proxy_mock.aircraft.route.return_value = route_info

        resp = test_flask_client.get(f"{endpoint_path}{callsign_str}")
        assert resp.status_code == HTTPStatus.OK
        assert resp.json == {
            utils.CALLSIGN_LABEL: "TEST",
            "route_name": route_info[0],
            "next_waypoint": route_info[1],
            "route_waypoints": route_info[2],
        }
Exemple #13
0
"""
from http import HTTPStatus
from unittest import mock

import bluebird.api.resources.utils.utils as utils
from bluebird.sim_proxy.proxy_simulator_controls import ProxySimulatorControls
from bluebird.sim_proxy.sim_proxy import SimProxy
from tests.data import TEST_SCENARIO
from tests.unit.api.resources import endpoint_path
from tests.unit.api.resources import patch_utils_path

_ENDPOINT = "scenario"
_ENDPOINT_PATH = endpoint_path(_ENDPOINT)


@mock.patch(patch_utils_path(_ENDPOINT), wraps=utils, spec_set=True)
def test_scenario_post(utils_patch, test_flask_client):
    """Tests the POST method"""

    sim_proxy_mock = mock.create_autospec(SimProxy, spec_set=True)
    utils_patch.sim_proxy.return_value = sim_proxy_mock
    simulation_mock = mock.create_autospec(ProxySimulatorControls,
                                           spec_set=True)
    type(sim_proxy_mock).simulation = mock.PropertyMock(
        return_value=simulation_mock)
    sector_mock = mock.PropertyMock(return_value=None)
    type(simulation_mock).sector = sector_mock

    # Test arg parsing

    resp = test_flask_client.post(_ENDPOINT_PATH)
Exemple #14
0
def test_eplog_get(test_flask_client):
    """Tests the GET method"""

    # Test arg parsing

    bb_logging.EP_FILE = None
    resp = test_flask_client.get(_ENDPOINT_PATH)
    assert resp.status_code == HTTPStatus.BAD_REQUEST
    assert resp.data.decode() == "No episode being recorded"

    with mock.patch("bluebird.api.resources.eplog.in_agent_mode"
                    ) as in_agent_mode_patch:

        in_agent_mode_patch.return_value = False

        # Test agent mode check

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode(
        ) == "Episode data only recorded when in Agent mode"

        # Test episode file check

        in_agent_mode_patch.return_value = True

        resp = test_flask_client.get(_ENDPOINT_PATH)
        assert resp.status_code == HTTPStatus.BAD_REQUEST
        assert resp.data.decode() == "No episode being recorded"

        with mock.patch(
                "bluebird.api.resources.eplog.bb_logging") as bb_logging_patch:

            bb_logging_patch.EP_FILE = Path("missing.log")

            with mock.patch(patch_utils_path(_ENDPOINT)) as utils_patch:

                sim_proxy_mock = mock.Mock()
                utils_patch.sim_proxy.return_value = sim_proxy_mock

                # Test error from simulation reset

                sim_proxy_mock.simulation.reset.return_value = "Error"

                resp = test_flask_client.get(f"{_ENDPOINT_PATH}?close_ep=True")
                assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
                assert resp.data.decode().startswith(
                    "Couldn't reset simulation: Error")

                # Test missing file

                sim_proxy_mock.simulation.reset.return_value = None

                resp = test_flask_client.get(f"{_ENDPOINT_PATH}?close_ep=True")
                assert resp.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
                assert resp.data.decode().startswith(
                    "Could not find episode file")

                # Test valid response

                bb_logging_patch.EP_FILE = TEST_EPISODE_LOG_FILE
                bb_logging_patch.EP_ID = 123

                resp = test_flask_client.get(f"{_ENDPOINT_PATH}?close_ep=True")
                assert resp.status_code == HTTPStatus.OK
                assert resp.json == {
                    "cur_ep_id": 123,
                    "cur_ep_file": str(TEST_EPISODE_LOG_FILE.absolute()),
                    "log": TEST_EPISODE_LOG,
                }