Esempio n. 1
0
def test_post_new_pokemon_which_doesnt_exist(test_client):
    assert Pokemon.objects().count() == 0

    response = test_client.post('/api/pokemon/', json={"name": "doesnt_exist"})
    assert response.status_code == 404

    assert Pokemon.objects().count() == 0
Esempio n. 2
0
def test_return_all_pokemons_is_a_list(db, ekans, hitmonlee):
    assert Pokemon.objects().count() == 0
    assert isinstance(PokemonService.get_all_pokemons(), list)
    Pokemon(**ekans).save()
    assert isinstance(PokemonService.get_all_pokemons(), list)
    Pokemon(**hitmonlee).save()
    assert isinstance(PokemonService.get_all_pokemons(), list)
Esempio n. 3
0
def test_get_pokemon_encounters_if_id_doesnt_exist(db, encounter):
    assert Pokemon.objects().count() == 0

    PokemonService.add_pokemon_encounter(23, encounter)

    assert Pokemon.objects().count() == 1
    assert Pokemon.objects().first().name == 'ekans'
Esempio n. 4
0
def test_get_pokemon_by_id(db, snorlax):
    assert Pokemon.objects().count() == 0

    Pokemon(**snorlax).save()
    mongo_pokemon = PokemonService.get_by_id(143)

    assert mongo_pokemon['weight'] == snorlax['weight']
    assert mongo_pokemon['height'] == snorlax['height']
Esempio n. 5
0
def test_post_new_encounter(test_client):
    assert Pokemon.objects().count() == 0

    test_client.post('/api/pokemon/', json={"name": "ekans"})
    response = test_client.post('/pokemon/23/encounters', json={"place": "city"})

    assert response.status_code == 201
    assert Pokemon.objects(name='ekans').first().encounters[0]['place'] == 'city'
Esempio n. 6
0
def test_saving_pokemon_to_db(db, ekans, hitmonlee, snorlax):
    assert Pokemon.objects().count() == 0

    for pokemon in (ekans, hitmonlee, snorlax):
        Pokemon(**pokemon).save()

    assert Pokemon.objects().count() == 3
    assert set(ekans.keys()).issubset(
        Pokemon.objects(name='ekans').first()._fields)
Esempio n. 7
0
def db():
    """
    This fixture will mock the MongoDB testing instance and pass it for testing. After each test is done, it will delete
    it so we will have clean database for next tests.
    :yield: connection to mocked MongoDB
    """

    # Creating new database
    connect('mongoengine', host='mongomock://localhost', alias='pokemonapi')

    # Yielding connection to tests
    yield

    # Teardown of created db
    Pokemon.drop_collection()
Esempio n. 8
0
def test_add_pokemon_encounter(db, ekans):

    Pokemon(**ekans).save()
    encounter = {
        'place': 'city',
        'note': 'Ekans was waiting on the sidewalk for someone.'
    }

    PokemonService.add_pokemon_encounter(pokemon_id=23,
                                         encounter_json=encounter)

    mongo_encounter = Pokemon.objects(name='ekans').first().encounters[0]

    assert mongo_encounter.place == encounter['place']
    assert mongo_encounter.note == encounter['note']
    assert mongo_encounter.timestamp
Esempio n. 9
0
    def get_all_pokemons() -> List[dict]:
        """
        Return all Pokemons saved in the database in a required format.
        :return: Response object containing list of all Pokemon documents saved in the database
        """

        return [pokemon.to_mongo().to_dict() for pokemon in Pokemon.objects()]
Esempio n. 10
0
def test_client():

    flask_app = create_app(test=True,
                           mongo_config=dict(
                               MONGODB_DB='mongoengine_mock',
                               MONGODB_HOST='mongomock://localhost',
                               MONGODB_ALIAS='pokemon_api'
                           ))

    # Create a test client using the Flask application configured for testing
    with flask_app.test_client() as testing_client:
        # Establish an application context
        with flask_app.app_context():
            yield testing_client

    Pokemon.drop_collection()
Esempio n. 11
0
def test_post_new_pokemon_which_already_exists(test_client):
    assert Pokemon.objects().count() == 0

    test_client.post('/api/pokemon/', json={"name": "ekans"})
    response = test_client.post('/api/pokemon/', json={"name": "ekans"})

    assert response.status_code == 200
    assert {'base_experience', 'name', 'height', 'weight', 'sprites', 'id'}.issubset(json.loads(response.data))
Esempio n. 12
0
def test_post_new_pokemon(test_client):
    assert Pokemon.objects().count() == 0

    response = test_client.post('/api/pokemon/', json={"name": "ekans"})
    assert response.status_code == 201
    assert json.loads(response.data) is None

    pokemon_in_db = json.loads(test_client.get('/api/pokemon/').data)
    assert pokemon_in_db[0]['name'] == 'ekans'
Esempio n. 13
0
def test_return_all_pokemons_has_all_specified_fields(db, ekans, snorlax):
    assert Pokemon.objects().count() == 0

    # '_id' field is renamed to 'id' on the API layer, just before returning to client.
    specified_fields = {
        "base_experience", "height", "_id", "name", "sprites", "weight"
    }
    specified_sprite_fields = {
        "back_default", "back_female", "back_shiny", "back_shiny_female",
        "front_default", "front_female", "front_shiny", "front_shiny_female"
    }

    for pokemon in (ekans, snorlax):
        Pokemon(**pokemon).save()

    pokemons = [pokemon.to_mongo().to_dict() for pokemon in Pokemon.objects()]

    assert all([
        specified_fields.issubset(pokemon.keys())
        and specified_sprite_fields.issubset(pokemon['sprites'].keys())
        for pokemon in pokemons
    ])
Esempio n. 14
0
def test_get_all_encounters(test_client):
    assert Pokemon.objects().count() == 0

    test_client.post('api/pokemon/', json={"name": "ekans"})
    test_client.post('/pokemon/23/encounters', json={"place": "city"})

    response = test_client.get(r'/pokemon/23/encounters')
    returned_data = json.loads(response.data)

    assert isinstance(returned_data, list)
    assert len(returned_data) == 1
    assert 'timestamp' in returned_data[0]
    assert returned_data[0]['place'] == 'city'
Esempio n. 15
0
    def get_by_id(pokemon_id: int) -> Pokemon:
        """
        Searching database for Pokemon with given id value. Raise NonExistingPokemon error if not found.
        :param pokemon_id: id of Pokemon that needs to be returned
        :return: Pokemon Object with given id
        """

        pokemon = Pokemon.objects(id=pokemon_id).first()

        if not pokemon:
            raise NonExistingPokemon

        return pokemon
Esempio n. 16
0
def test_get_pokemon_encounters(db, ekans):

    Pokemon(**ekans).save()
    encounter = {
        'place': 'city',
        'note': 'Ekans was waiting on the sidewalk for someone.'
    }

    for _ in range(5):
        PokemonService.add_pokemon_encounter(23, encounter_json=encounter)

    mongo_encounters = PokemonService.get_all_encounters(23)

    assert len(mongo_encounters) == 5
    assert isinstance(mongo_encounters, list)
    assert all(['timestamp' in encounter for encounter in mongo_encounters])
Esempio n. 17
0
    def save_pokemon(pokemon: dict) -> Pokemon:
        """
        Create Pokemon object from given dictionary.
        If dictionary contain keys that are not specified in the schema, they will be omitted.
        :param pokemon: dictionary with Pokemon information.
        """

        Pokemon(id=pokemon['id'],
                name=pokemon['name'],
                weight=pokemon['weight'],
                height=pokemon['height'],
                base_experience=pokemon['base_experience'],
                sprites=Sprite.pick_specified_fields(
                    pokemon['sprites'])).save()

        logging.getLogger('PokemonAPI').info(
            f"{pokemon['name']} created in the database")
Esempio n. 18
0
def test_get_all_encounters_for_missing_id(test_client):
    assert Pokemon.objects().count() == 0

    response = test_client.get('/pokemon/23/encounters')
    assert response.status_code == 404
Esempio n. 19
0
def test_add_pokemon_encounter_with_invalid_data(db, ekans, encounter_json):

    Pokemon(**ekans).save()
    with pytest.raises(InvalidPayload):
        PokemonService.add_pokemon_encounter(pokemon_id=23,
                                             encounter_json=encounter_json)