예제 #1
0
 def test_find_by_availability(self):
     """ Find a Pet by Availability """
     Pet(0, "fido", "dog", False).save()
     Pet(0, "kitty", "cat", True).save()
     pets = Pet.find_by_availability(True)
     self.assertEqual(len(pets), 1)
     self.assertEqual(pets[0].name, "kitty")
예제 #2
0
 def test_find_by_category(self):
     Pet(0, "fido", "dog").save()
     Pet(0, "kitty", "cat").save()
     pets = Pet.find_by_category("cat")
     self.assertNotEqual(len(pets), 0)
     self.assertEqual(pets[0].category, "cat")
     self.assertEqual(pets[0].name, "kitty")
예제 #3
0
 def test_find_pet(self):
     Pet(0, "fido", "dog").save()
     Pet(0, "kitty", "cat").save()
     pet = Pet.find(2)
     self.assertIsNot(pet, None)
     self.assertEqual(pet.id, 2)
     self.assertEqual(pet.name, "kitty")
예제 #4
0
 def test_find_by_name(self):
     """ Find a Pet by Name """
     Pet(name="fido", category="dog", available=True).save()
     Pet(name="kitty", category="cat", available=False).save()
     pets = Pet.find_by_name("kitty")
     self.assertEqual(pets[0].category, "cat")
     self.assertEqual(pets[0].name, "kitty")
     self.assertEqual(pets[0].available, False)
예제 #5
0
 def test_deserialize_a_pet(self):
     data = {"id": 1, "name": "kitty", "category": "cat"}
     pet = Pet(data['id'])
     pet.deserialize(data)
     self.assertNotEqual(pet, None)
     self.assertEqual(pet.id, 1)
     self.assertEqual(pet.name, "kitty")
     self.assertEqual(pet.category, "cat")
예제 #6
0
 def setUp(self):
     """ Runs before each test """
     service.init_db()
     db.drop_all()  # clean up the last tests
     db.create_all()  # create new tables
     Pet(name='fido', category='dog', available=True).save()
     Pet(name='kitty', category='cat', available=True).save()
     self.app = service.app.test_client()
예제 #7
0
 def test_find_by_name(self):
     """ Find a Pet by Name """
     Pet(0, "fido", "dog").save()
     Pet(0, "kitty", "cat").save()
     pets = Pet.find_by_name("fido")
     self.assertNotEqual(len(pets), 0)
     self.assertEqual(pets[0].category, "dog")
     self.assertEqual(pets[0].name, "fido")
예제 #8
0
 def test_find_by_name(self):
     """ Find a Pet by Name """
     Pet(name="fido", category_id=TestPets.dog.id, available=True).save()
     Pet(name="kitty", category_id=TestPets.cat.id, available=False).save()
     pets = Pet.find_by_name("kitty")
     self.assertEqual(pets[0].category_id, TestPets.cat.id)
     self.assertEqual(pets[0].name, "kitty")
     self.assertEqual(pets[0].available, False)
예제 #9
0
 def test_deserialize_a_pet(self):
     """ Test deserialization of a Pet """
     data = {"id": 1, "name": "kitty", "category": "cat", "available": True}
     pet = Pet()
     pet.deserialize(data)
     self.assertNotEqual(pet, None)
     self.assertEqual(pet.id, None)
     self.assertEqual(pet.name, "kitty")
     self.assertEqual(pet.category, "cat")
     self.assertEqual(pet.available, True)
예제 #10
0
 def test_serialize_a_pet(self):
     pet = Pet(0, "fido", "dog")
     data = pet.serialize()
     self.assertNotEqual(data, None)
     self.assertIn('id', data)
     self.assertEqual(data['id'], 0)
     self.assertIn('name', data)
     self.assertEqual(data['name'], "fido")
     self.assertIn('category', data)
     self.assertEqual(data['category'], "dog")
예제 #11
0
 def test_for_case_insensitive(self):
     """ Test for Case Insensitive Search """
     Pet(0, "Fido", "DOG").save()
     Pet(0, "Kitty", "CAT").save()
     pets = Pet.find_by_name("fido")
     self.assertNotEqual(len(pets), 0)
     self.assertEqual(pets[0].name, "Fido")
     pets = Pet.find_by_category("cat")
     self.assertNotEqual(len(pets), 0)
     self.assertEqual(pets[0].category, "CAT")
예제 #12
0
 def test_serialize_a_pet(self):
     """ Serialize a Pet """
     pet = Pet("fido", "dog", False)
     data = pet.serialize()
     self.assertNotEqual(data, None)
     self.assertNotIn('_id', data)
     self.assertIn('name', data)
     self.assertEqual(data['name'], "fido")
     self.assertIn('category', data)
     self.assertEqual(data['category'], "dog")
     self.assertIn('available', data)
     self.assertEqual(data['available'], False)
예제 #13
0
 def setUp(self):
     # Create some categories for the tests
     server.truncate_db()
     # Create some categories for testing
     dog = Category(name="Dog")
     dog.save()
     self.dog_id = dog.id
     cat = Category(name="Cat")
     cat.save()
     self.cat_id = cat.id
     Pet(name='fido', category_id=self.dog_id, available=True).save()
     Pet(name='kitty', category_id=self.cat_id, available=True).save()
     self.app = server.app.test_client()
    def get(self):
        """ Returns all of the Pets """
        app.logger.info('Request to list Pets...')
        pets = []
        category = request.args.get('category')
        if category:
            pets = Pet.find_by_category(category)
        else:
            pets = Pet.all()

        app.logger.info('[%s] Pets returned', len(pets))
        results = [pet.serialize() for pet in pets]
        return results, status.HTTP_200_OK
예제 #15
0
 def test_serialize_a_pet(self):
     """ Test serialization of a Pet """
     pet = Pet(name="fido", category="dog", available=False)
     data = pet.serialize()
     self.assertNotEqual(data, None)
     self.assertIn('id', data)
     self.assertEqual(data['id'], None)
     self.assertIn('name', data)
     self.assertEqual(data['name'], "fido")
     self.assertIn('category', data)
     self.assertEqual(data['category'], "dog")
     self.assertIn('available', data)
     self.assertEqual(data['available'], False)
예제 #16
0
 def test_delete_a_pet(self):
     pet = Pet(0, "fido", "dog")
     pet.save()
     self.assertEqual(len(Pet.all()), 1)
     # delete the pet and make sure it isn't in the database
     pet.delete()
     self.assertEqual(len(Pet.all()), 0)
예제 #17
0
def list_pets():
    """ Returns all of the Pets """
    pets = []
    category = request.args.get('category')
    name = request.args.get('name')
    if category:
        pets = Pet.find_by_category(category)
    elif name:
        pets = Pet.find_by_name(name)
    else:
        pets = Pet.all()

    results = [pet.serialize() for pet in pets]
    return make_response(jsonify(results), status.HTTP_200_OK)
예제 #18
0
 def test_delete_a_pet(self):
     """ Delete a Pet """
     pet = Pet(name="fido", category="dog", available=True)
     pet.save()
     self.assertEqual(len(Pet.all()), 1)
     # delete the pet and make sure it isn't in the database
     pet.delete()
     self.assertEqual(len(Pet.all()), 0)
예제 #19
0
def create_pet():
    """
    Create new pet
    """
    form = CreatePetForm()
    form["csrf_token"].data = request.cookies["csrf_token"]

    image_error = []
    image = request.files.get("image", None)

    if image != None:
        image.filename = secure_filename(image.filename)
        pattern = re.compile(".*(apng|avif|jpe?g|png|svg|webp)$",
                             re.IGNORECASE)
        is_image = bool(pattern.match(image.mimetype))
        if not is_image:
            image_error.append(
                "Upload must be an image (apng, avif, jpeg/jpg, png, svg, webp)."
            )

    if form.validate_on_submit() and not image_error:

        output_link = (
            upload_file_to_s3(image) if image else
            "https://pair-yo-pet-aws.s3-us-west-1.amazonaws.com/default-dog.png"
        )

        new_pet = Pet(
            userId=form.data["userId"],
            name=form.data["name"],
            petType=form.data["petType"],
            age=form.data["age"],
            imageURL=output_link,
            energy=form.data["energy"],
            social=form.data["social"],
            behaved=form.data["behaved"],
            size=form.data["size"],
            env=form.data["env"],
            description=form.data["description"],
        )
        db.session.add(new_pet)
        db.session.commit()
        return new_pet.to_dict()

    errors = validation_errors_to_error_messages(form.errors)
    errors += image_error

    return {"errors": errors}
예제 #20
0
 def test_update_pet_with_text_data(self):
     """ Update a Pet with text data """
     pet = Pet.find_by_name('kitty')[0]
     resp = self.app.put('/pets/{}'.format(pet.id),
                         data="hello",
                         content_type='text/plain')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
예제 #21
0
 def test_update_pet_with_no_data(self):
     """ Update a Pet with no data passed """
     pet = Pet.find_by_name('kitty')[0]
     resp = self.app.put('/pets/{}'.format(pet.id),
                         data=None,
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
예제 #22
0
 def test_create_a_pet(self):
     # Create a pet and assert that it exists
     pet = Pet(0, "fido", "dog")
     self.assertNotEqual(pet, None)
     self.assertEqual(pet.id, 0)
     self.assertEqual(pet.name, "fido")
     self.assertEqual(pet.category, "dog")
예제 #23
0
 def test_create_a_pet(self):
     """ Create a pet and assert that it exists """
     pet = Pet(0, "fido", "dog")
     self.assertTrue(pet != None)
     self.assertEqual(pet.id, 0)
     self.assertEqual(pet.name, "fido")
     self.assertEqual(pet.category, "dog")
예제 #24
0
def fake_big_update_pets_location(event, context):
    step = 0.000700
    try:
        sqs = boto3.resource('sqs')
        queue = sqs.get_queue_by_name(QueueName=os.environ.get('PET_QUEUE'))

        pets = [pet for pet in Pet.scan()]
        for pet in pets:
            body = json.dumps({
                'owner': pet.owner,
                'name': pet.name,
                'at': datetime.timestamp(datetime.now()),
                'position': {
                    'lat':
                    pet.location.position.lat -
                    step if randint(0, 1) else pet.location.position.lat +
                    step,
                    'lng':
                    pet.location.position.lng -
                    step if randint(0, 1) else pet.location.position.lng + step
                }
            })
            queue.send_message(MessageAttributes={
                'Kind': {
                    'DataType': 'String',
                    'StringValue': 'location-update'
                }
            },
                               MessageBody=(body))
            print('update location for : {0}'.format(pet.name))

    except Exception as ex:
        print(ex)
예제 #25
0
 def test_create_a_pet(self):
     """ Create a pet and assert that it exists """
     pet = Pet(0, "fido", "dog", False)
     self.assertNotEqual(pet, None)
     self.assertEqual(pet.id, 0)
     self.assertEqual(pet.name, "fido")
     self.assertEqual(pet.category, "dog")
     self.assertEqual(pet.available, False)
예제 #26
0
 def test_update_pet_with_no_name(self):
     """ Update a Pet without a name """
     pet = Pet.find_by_name('kitty')[0]
     new_pet = {'category_id': self.dog_id}
     resp = self.app.put('/pets/{}'.format(pet.id),
                         json=new_pet,
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
예제 #27
0
 def test_create_a_pet(self):
     """ Create a pet and assert that it exists """
     pet = Pet(name="fido", category="dog", available=True)
     self.assertTrue(pet != None)
     self.assertEqual(pet.id, None)
     self.assertEqual(pet.name, "fido")
     self.assertEqual(pet.category, "dog")
     self.assertEqual(pet.available, True)
예제 #28
0
 def test_key_error_on_update(self, bad_mock):
     """ Test KeyError on update """
     bad_mock.side_effect = KeyError()
     pet = Pet("fido", "dog", False)
     pet.save()
     pet.name = 'Fifi'
     pet.update()
예제 #29
0
def create_pets():
    """
    Creates a Pet
    This endpoint will create a Pet based the data in the body that is posted
    """
    data = {}
    # Check for form submission data
    if request.headers.get(
            'Content-Type') == 'application/x-www-form-urlencoded':
        app.logger.info('Getting data from form submit')
        data = {
            'name': request.form['name'],
            'category': request.form['category'],
            'available': True
        }
    else:
        app.logger.info('Getting data from API call')
        data = request.get_json()
    app.logger.info(data)
    pet = Pet()
    pet.deserialize(data)
    pet.save()
    message = pet.serialize()
    location_url = url_for('get_pets', pet_id=pet.id, _external=True)
    return make_response(jsonify(message), status.HTTP_201_CREATED,
                         {'Location': location_url})
예제 #30
0
 def test_get_pet(self):
     """ Get a single Pet """
     # get the id of a pet
     pet = Pet.find_by_name('fido')[0]
     resp = self.app.get('/pets/{}'.format(pet.id),
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     data = resp.get_json()
     self.assertEqual(data['name'], pet.name)