def test_create_order_with_valid_details_endpoint(self):
        LocationFactory.create(id=1, zone='+1')
        order = OrderFactory.create()
        menu = MenuFactory.create()
        meal_item1 = MealItemFactory.create()
        meal_item2 = MealItemFactory.create()
        meal_item3 = MealItemFactory.create()
        meal_item1.meal_type = MealTypes.protein
        meal_item2.meal_type = MealTypes.main

        meal_items = [meal_item1.id, meal_item2.id, meal_item3.id]
        data = {'userId': order.user_id, 'dateBookedFor': (date.today() + timedelta(days=2)).strftime('%Y-%m-%d'),
                'dateBooked': order.date_booked.strftime('%Y-%m-%d'), 'channel': 'web', 'menuId': menu.id,
                'mealPeriod': order.meal_period, 'mealItems': meal_items}

        response = self.client().post(
            self.make_url('/orders/'), data=self.encode_to_json_string(data), headers=self.headers())

        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        payload = response_json['payload']
        self.assertEqual(response.status_code, 201)
        self.assertJSONKeyPresent(response_json, 'payload')
        self.assertEqual(payload['order']['userId'], BaseTestCase.user_id())
        self.assertEqual(payload['order']['channel'], 'web')
    def test_create_order_with_invalid_details_endpoint(self):
        items = [item.id for item in MealItemFactory.create_batch(4)]
        menu = MenuFactory.create()
        LocationFactory.create(id=1, zone='+1')
        data = {
            'dateBookedFor':
            (date.today() + timedelta(days=-3)).strftime('%Y-%m-%d'),
            'channel':
            'web',
            'mealPeriod':
            'lunch',
            'menuId':
            menu.id
        }

        # If we don't add meal items
        response = self.client().post(self.make_url('/orders/'),
                                      data=self.encode_to_json_string(data),
                                      headers=self.headers())
        self.assert400(response)

        # If we book in the past
        data.update({'mealItems': items})
        response1 = self.client().post(self.make_url('/orders/'),
                                       data=self.encode_to_json_string(data),
                                       headers=self.headers())
        self.assert400(response1)
        data.update({
            'dateBookedFor':
            (date.today() + timedelta(days=2)).strftime('%Y-%m-%d')
        })
        response2 = self.client().post(self.make_url('/orders/'),
                                       data=self.encode_to_json_string(data),
                                       headers=self.headers())
        self.assertEqual(response2.status_code, 201)
    def test_delete_engagement_with_associated_menus(self):
        datetime.now().date()
        location = LocationFactory()
        location.save()
        meal_item = MealItemFactory(location=location)
        vendor = VendorFactory(location=location)
        engagement = VendorEngagementFactory.create(location=location, vendor=vendor)
        menu_repo = MenuRepo()
        menu_repo.new_menu(
            date='2018-10-15',
            meal_period='lunch',
            main_meal_id=meal_item.id,
            allowed_side=1,
            allowed_protein=1,
            side_items=[2],
            protein_items=[3],
            vendor_engagement_id=engagement.id,
            location_id=location.id
        )

        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='delete_engagement', role=role)
        UserRoleFactory.create(user_id=user_id, role=role, location_id=location.id)

        response = self.client().delete(self.make_url(f'/engagements/{engagement.id}'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assert400(response)

        self.assertEqual(response_json['msg'], 'This engagement cannot be deleted because it has a child object')
    def test_interactions_after_final_meal_selection_valid(
        self,
        mock_json_loads,
        mock_user_info,
        mock_andela_service,
        mock_menu_repo,
        mock_engagement_repo,
        mock_post
    ):
        location = LocationFactory.create()
        location.save()
        meal = MealItemFactory.create()
        meal.save()
        submit_rating['state'] = f'{meal.id}_breakfast_2019-02-20_rate_{location.id}_1'

        mock_json_loads.return_value = submit_rating
        mock_user_info.return_value = {'user': {'profile': {'email': '*****@*****.**'}}}
        mock_andela_service.return_value = {'id': 'victor_adukwu_andela_com'}
        engagement = VendorEngagementFactory.create()
        engagement.save()
        mock_engagement_repo.return_value = engagement
        mock_menu_repo.return_value = self	.menu_factory.create()
        response = self.client().post(self.make_url(f'/bot/interactions/'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))
        mock_post.assert_called_once()
        self.assert200(response)
        self.assertEqual(response_json['type'], 'dialog_submission')
    def test_create_user_role_endpoint(self, mock_andela_get_user_by_email):
        location = LocationFactory.create()
        user = UserFactory()
        mock_andela_get_user_by_email.return_value = {'id': user.user_id}

        create_user_role('create_user_roles')

        new_role = RoleFactory.create()

        user_role_data = {
            'roleId': new_role.id,
            'emailAddress': self.user_email()
        }
        headers = self.headers()
        headers.update({'X-Location': location.id})
        response = self.client().post(
            self.make_url(f'/roles/user'),
            data=self.encode_to_json_string(user_role_data),
            headers=headers)

        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response_json['msg'], 'OK')
        self.assertEqual(response_json['payload']['user_role']['roleId'],
                         new_role.id)
Beispiel #6
0
    def test_create_meal_item_endpoint_with_right_permission(self):
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        location = LocationFactory.create()
        PermissionFactory.create(keyword='create_meal_item', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)
        meal_item = MealItemFactory.build(location=location)

        headers = self.headers()
        headers.update({'X-Location': location.id})

        data = {'mealName': meal_item.name, 'image': meal_item.image,
                'mealType': meal_item.meal_type}
        response = self.client().post(
            self.make_url('/meal-items/'), 
            data=self.encode_to_json_string(data),
            headers=headers
        )
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        payload = response_json['payload']

        self.assertEqual(response.status_code, 201)

        self.assertJSONKeyPresent(response_json, 'payload')
        self.assertEqual(payload['mealItem']['name'], meal_item.name)
        self.assertEqual(payload['mealItem']['image'], meal_item.image)
        self.assertEqual(payload['mealItem']['mealType'], meal_item.meal_type)
    def test_list_order_by_page_endpoint(self, mock_andela_service):
        location = LocationFactory()
        OrderFactory.create_batch(3, location=location)
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='view_orders', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        mock_andela_service.return_value = {
            'id': user_id,
            'first_name': fake.first_name(),
            'last_name': fake.last_name()
        }

        headers = self.headers()
        headers.update({'X-Location': location.id})

        response = self.client().get(self.make_url('/orders/'), query_string={'per_page': 2, 'page': 1}, headers=headers)
        decoded = loads(response.data, encoding='utf-8')
        self.assert200(response)
        self.assertEqual(decoded['payload']['meta']['current_page'], 1)
        self.assertEqual(len(decoded['payload']['orders']), 2)

        response1 = self.client().get(self.make_url('/orders/'), query_string={'per_page': 2, 'page': 2}, headers=headers)
        self.assert200(response1)
        decoded1 = loads(response1.data, encoding='utf-8')
        self.assertEqual(decoded1['payload']['meta']['current_page'], 2)
        self.assertEqual(len(decoded1['payload']['orders']), 1)
    def test_create_user_endpoint_succeeds(self):
        create_user_role('create_user')
        user = UserFactory.create(user_id="user_id_2", is_deleted=True)
        role = RoleFactory(name='test_role')

        location = LocationFactory.create()
        headers = self.headers()
        headers.update({'X-Location': location.id})

        user_data = dict(
            firstName=user.first_name,
            lastName=user.last_name,
            roleId=role.id
        )

        response = self.client().post(
            self.make_url("/users/"),
            headers=headers,
            data=self.encode_to_json_string(user_data))

        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response_json['msg'], "OK")
        self.assertEqual(response_json['payload']['user']['firstName'], user.first_name)
        self.assertEqual(response_json['payload']['user']['lastName'], user.last_name)
        self.assertEqual(response_json['payload']['user']['userRoles'][0]['name'], role.name)
        self.assertEqual(response_json['payload']['user']['userRoles'][0]['help'], role.help)
Beispiel #9
0
    def test_list_menu_endpoint_with_invalid_date_fails(self):
        """Test that users with the wrong date fails"""
        meal_item_repo = MealItemRepo()
        location = LocationFactory.create()

        main_meal_item = meal_item_repo.new_meal_item(name="main1",
                                                      image="image1",
                                                      meal_type="main",
                                                      location_id=location.id)
        side_meal_item = meal_item_repo.new_meal_item(name="side1",
                                                      image="image11",
                                                      meal_type="side",
                                                      location_id=location.id)
        protein_meal_item = meal_item_repo.new_meal_item(
            name="protein1",
            image="image12",
            meal_type="protein",
            location_id=location.id)

        menu = MenuFactory.create(main_meal_id=main_meal_item.id,
                                  side_items=str(side_meal_item.id),
                                  protein_items=str(protein_meal_item.id))

        date = '201502-24'

        response = self.client().get(
            self.make_url(f'/menus/{menu.meal_period}/{date}/{date}'),
            headers=self.headers())
        self.assert400(response)
Beispiel #10
0
    def test_list_menu_range_endpoint_with_right_permission_wrong_period(self):
        location = LocationFactory()
        meal_item_repo = MealItemRepo()
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='view_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)
        current_date = datetime.now().date()
        start_date = current_date.strftime('%Y-%m-%d')
        end_date = (datetime.now().date() +
                    timedelta(days=7)).strftime('%Y-%m-%d')

        side_meal_item = meal_item_repo.new_meal_item(name="side1",
                                                      image="image11",
                                                      meal_type="side",
                                                      location_id=location.id)
        protein_meal_item = meal_item_repo.new_meal_item(
            name="protein1",
            image="image12",
            meal_type="protein",
            location_id=location.id)
        MenuFactory.create_batch(5,
                                 side_items=side_meal_item.id,
                                 protein_items=protein_meal_item.id)

        response = self.client() \
            .get(self.make_url(f'/admin/menus/wrong_period/{start_date}/{end_date}'), headers=self.headers())
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assert400(response)
        self.assertEqual(response_json['msg'],
                         'Provide valid meal period and date range')
    def test_immediate_past_engagement_no_past_engagement(self):

        location = LocationFactory()
        location.save()
        vendor = VendorFactory.create(location=location)
        vendor.save()
        engagement1 = VendorEngagementFactory.create(vendor_id=vendor.id, end_date=datetime.now()+timedelta(10), location=location)
        engagement2 = VendorEngagementFactory.create(vendor_id=vendor.id, end_date=datetime.now()+timedelta(14), location=location)
        engagement1.save()
        engagement2.save()

        response = self.client().get(self.make_url(f'/engagements/past/{location.id}'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assert404(response)
        self.assertEqual(response_json['msg'], 'No past engagement for this location')
Beispiel #12
0
    def test_list_menu_range_endpoint_with_right_permission(self):
        """ Test that users with right permission can view list of menu with date range """
        location = LocationFactory.create()
        meal_item_repo = MealItemRepo()
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='view_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)
        current_date = datetime.now().date()
        start_date = current_date.strftime('%Y-%m-%d')
        end_date = (datetime.now().date() +
                    timedelta(days=7)).strftime('%Y-%m-%d')

        side_meal_item = meal_item_repo.new_meal_item(name="side1",
                                                      image="image11",
                                                      meal_type="side",
                                                      location_id=location.id)
        protein_meal_item = meal_item_repo.new_meal_item(
            name="protein1",
            image="image12",
            meal_type="protein",
            location_id=location.id)
        MenuFactory.create_batch(5,
                                 side_items=side_meal_item.id,
                                 protein_items=protein_meal_item.id,
                                 location=location)

        response = self.client() \
            .get(self.make_url(f'/admin/menus/{MealPeriods.lunch}/{start_date}/{end_date}'), headers=self.headers())

        self.assert200(response)
Beispiel #13
0
    def test_create_vendor_endpoint(self):
        location = LocationFactory(id=self.headers()['X-Location'])
        vendor = VendorFactory.build()
        data = {
            'name': vendor.name,
            'address': vendor.address,
            'tel': vendor.tel,
            'isActive': vendor.is_active,
            'contactPerson': vendor.contact_person
        }
        response = self.client().post(self.make_url('/vendors/'),
                                      data=self.encode_to_json_string(data),
                                      headers=self.headers())
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        payload = response_json['payload']

        self.assertEqual(response.status_code, 201)
        self.assertJSONKeyPresent(response_json, 'payload')
        self.assertEqual(payload['vendor']['name'], vendor.name)
        self.assertEqual(payload['vendor']['tel'], vendor.tel)
        self.assertEqual(payload['vendor']['contactPerson'],
                         vendor.contact_person)
        self.assertEqual(payload['vendor']['address'], vendor.address)
Beispiel #14
0
    def test_create_user_endpoint_succeeds1(self):
        location = LocationFactory()
        create_user_role("create_user", "admin")

        user = UserFactoryFake.build()
        role1 = RoleFactory()
        user_data = dict(
            first_name=user.first_name,
            last_name=user.last_name,
            role_id=role1.id,
            email=user.email,
            gender=user.gender,
            date_of_birth=str(user.date_of_birth),
            location_id=location.id,
            password=user.password,
        )

        headers = self.headers()
        headers.update({"X-Location": location.id})

        response = self.client().post(
            self.make_url("/users/"),
            headers=headers,
            data=self.encode_to_json_string(user_data),
        )

        response_json = self.decode_from_json_string(response.data.decode("utf-8"))

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response_json["msg"], "OK")
        self.assertEqual(
            response_json["payload"]["user"]["first_name"], user.first_name
        )
        self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name)
Beispiel #15
0
    def test_list_meal_item_endpoint_correct_sort_order(self):
        # Create Three Dummy Vendors
        location = LocationFactory.create()
        meals = MealItemFactory.create_batch(3, location=location)

        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='view_meal_item', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        headers = self.headers()
        headers.update({'X-Location': location.id})

        response = self.client().get(self.make_url('/meal-items/'), headers=headers)
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))
        payload = response_json['payload']

        meals_sorted_by_name = sorted(
            [meal.name for meal in meals]
        )

        meals_returned = [meal.get("name") for meal in payload['mealItems']]

        self.assert200(response)
        self.assertEqual(len(payload['mealItems']), 3)
        self.assertJSONKeysPresent(payload['mealItems'][0], 'name', 'mealType', 'image')
        self.assertEqual(meals_returned[0], meals_sorted_by_name[0])
        self.assertEqual(meals_returned[1], meals_sorted_by_name[1])
        self.assertEqual(meals_returned[2], meals_sorted_by_name[2])
 def test_create_menu_template_with_permission_succeeds(self):
     self.create_admin()
     LocationFactory.create(id=1).save()
     data = {
         "name": "Name of the template",
         "mealPeriod": "lunch",
         "description": "somehting"
     }
     response = self.client().post(self.make_url("/menu_template/"),
                                   headers=self.headers(),
                                   data=self.encode_to_json_string(data))
     response_json = self.decode_from_json_string(
         response.data.decode('utf-8'))
     self.assertEqual(response.status_code, 201)
     self.assertEqual(response_json['msg'], 'OK')
     self.assertJSONKeysPresent(response_json['payload'], 'name')
     self.assertJSONKeysPresent(response_json['payload'], 'locationId')
Beispiel #17
0
    def __init__(self):
        self.player = Player()

        # Containers
        self.locations = []
        self.items = []
        self.characters = []
        self.map_elements = []

        # Factories
        self.character_factory = CharacterFactory()
        self.location_factory = LocationFactory()
        self.item_factory = ItemFactory()
        self.supply_factory = SupplyFactory()
        self.map_element_factory = MapElementFactory()

        self.map_rectangle = (0, 0, 0, 0)
    def test_get_menu_start_end_on_friday(self, mock_get):
        mock_get.return_value = datetime.strptime('2019-02-15', '%Y-%m-%d')

        result = self.bot_controller.get_menu_start_end_on(LocationFactory.build())

        self.assertEqual(type(result), tuple)
        self.assertEqual(result[0], datetime(2019, 2, 18, 0, 0))
        self.assertEqual(result[1], datetime(2019, 2, 22, 0, 0))
    def test_get_menu_start_end_on_saturday(self, mock_get):
        mock_get.return_value = datetime.strptime('2019-02-16 15:01', '%Y-%m-%d %H:%M')

        result = self.bot_controller.get_menu_start_end_on(LocationFactory.build())

        self.assertEqual(type(result), tuple)
        self.assertEqual(result[0].date(), datetime(2019, 2, 18).date())
        self.assertEqual(result[1].date(), datetime(2019, 2, 22).date())
Beispiel #20
0
 def setUp(self):
     self.BaseSetUp()
     self.menu_template = MenuTemplate(
         name='New Menu Template',
         location=LocationFactory(),
         meal_period='lunch',
         description="somehting about it"
     )
     self.menu_template.save()
Beispiel #21
0
    def test_update_menu_endpoint_with_wrong_protein_item_values(self):
        location = LocationFactory.create()
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='update_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        meal_item_repo = MealItemRepo()

        main_meal_item = meal_item_repo.new_meal_item(name="main1",
                                                      image="image1",
                                                      meal_type="main",
                                                      location_id=location.id)
        side_meal_item = meal_item_repo.new_meal_item(name="side1",
                                                      image="image11",
                                                      meal_type="side",
                                                      location_id=location.id)
        protein_meal_item = meal_item_repo.new_meal_item(
            name="protein1",
            image="image12",
            meal_type="protein",
            location_id=location.id)

        vendor = VendorFactory.build()
        vendor_engagement = VendorEngagementFactory.build(vendor_id=vendor.id)
        vendor_engagement.save()

        menu = MenuFactory.create(main_meal_id=main_meal_item.id,
                                  side_items=side_meal_item.id,
                                  protein_items=protein_meal_item.id)
        menu.vendor_engagement_id = vendor_engagement.id
        menu.save()

        data = {
            'date': menu.date.strftime('%Y-%m-%d'),
            'mealPeriod': menu.meal_period,
            'mainMealId': main_meal_item.id,
            'allowedSide': 2,
            'allowedProtein': 2,
            'sideItems': [side_meal_item.id],
            'proteinItems': [1000],
            'vendorEngagementId': vendor_engagement.id
        }

        response = self.client().put(self.make_url('/admin/menus/{}'.format(
            menu.id)),
                                     data=self.encode_to_json_string(data),
                                     headers=self.headers())
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assert400(response)
        self.assertEqual(
            response_json['msg'],
            'Bad Request - proteinItems contains invalid id(s) for meal_item table '
        )
Beispiel #22
0
    def test_update_menu_endpoint(self):
        """Test update of a menu"""
        location = LocationFactory()
        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='update_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        meal_item_repo = MealItemRepo()

        main_meal_item = meal_item_repo.new_meal_item(name="main1",
                                                      image="image1",
                                                      meal_type="main",
                                                      location_id=location.id)
        side_meal_item = meal_item_repo.new_meal_item(name="side1",
                                                      image="image11",
                                                      meal_type="side",
                                                      location_id=location.id)
        protein_meal_item = meal_item_repo.new_meal_item(
            name="protein1",
            image="image12",
            meal_type="protein",
            location_id=location.id)
        vendor = VendorFactory.build()
        vendor_engagement = VendorEngagementFactory.build(vendor_id=vendor.id)
        vendor_engagement.save()
        menu = MenuFactory.create(main_meal_id=main_meal_item.id,
                                  side_items=side_meal_item.id,
                                  protein_items=protein_meal_item.id,
                                  location=location)
        menu.save()
        data = {
            'date': menu.date.strftime('%Y-%m-%d'),
            'mealPeriod': menu.meal_period,
            'mainMealId': main_meal_item.id,
            'allowedSide': 2,
            'allowedProtein': 2,
            'sideItems': [side_meal_item.id],
            'proteinItems': [protein_meal_item.id],
            'vendorEngagementId': vendor_engagement.id
        }

        response = self.client().put(self.make_url('/admin/menus/{}'.format(
            menu.id)),
                                     data=self.encode_to_json_string(data),
                                     headers=self.headers())
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))
        payload = response_json['payload']

        self.assert200(response)
        self.assertEqual(payload['menu']['allowedProtein'],
                         data['allowedProtein'])
        self.assertEqual(payload['menu']['allowedSide'], data['allowedSide'])
    def test_interactions_after_selecting_location(self, mock_get_menu_start_end_on, mock_json_loads, mock_locationrepo_get):
        mock_json_loads.return_value = center_selected
        mock_get_menu_start_end_on.return_value = (datetime(2019, 2, 15), datetime(2019, 2, 15))
        mock_locationrepo_get.get.return_value = LocationFactory.create(id=1)

        response = self.client().post(self.make_url(f'/bot/interactions/'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assert200(response)
        self.assertEqual(response_json['type'], 'interactive_message')
        self.assertEqual(type(response_json['actions']), list)
Beispiel #24
0
    def test_delete_existing_location_succeeds(self):
        new_location = LocationFactory.create()

        response = self.client().delete(
            self.make_url(f'/locations/{new_location.id}'),
            headers=self.headers())

        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_json['msg'], 'Location deleted successfully')
    def test_list_vendor_engagement_endpoint(self):
        location = LocationFactory(id=self.headers()['X-Location'])
        VendorEngagementFactory.create_batch(4, location=location)

        response = self.client().get(self.make_url('/engagements/'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))
        payload = response_json['payload']

        self.assert200(response)
        self.assertEqual(len(payload['engagements']), 4)
        self.assertJSONKeysPresent(payload['engagements'][0], 'endDate', 'startDate', 'id', 'vendor',
                                   'terminationReason', 'timestamps')
	def test_list_vendors_endpoint(self):
		location = LocationFactory(id=self.headers()['X-Location'])
		# Create Three Dummy Vendors
		vendors = VendorFactory.create_batch(3, location_id=location.id)

		page_id = 1
		response = self.client().get(self.make_url('/vendors/'), headers=self.headers())
		response_json = self.decode_from_json_string(response.data.decode('utf-8'))
		payload = response_json['payload']
		
		self.assert200(response)
		self.assertEqual(len(payload['vendors']), 3)
		self.assertJSONKeysPresent(payload['vendors'][0], 'name', 'tel', 'id', 'address', 'contactPerson','timestamps')
Beispiel #27
0
    def test_get_location_succeeds(self):

        new_location = LocationFactory.create()

        response = self.client().get(self.make_url('/locations/'),
                                     headers=self.headers())

        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assert200(response)
        self.assertEqual(response_json['msg'], 'OK')
        self.assertEqual(response_json['payload']['locations'][0]['name'],
                         new_location.name)
Beispiel #28
0
    def test_list_meal_item_endpoint_wrong_permission(self):
        # Create Three Dummy Vendors
        meals = MealItemFactory.create_batch(3, location=LocationFactory())

        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='wrong_permission', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        response = self.client().get(self.make_url('/meal-items/'), headers=self.headers())
        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assert401(response)
        self.assertEqual(response_json['msg'], 'Access Error - Permission Denied')
Beispiel #29
0
    def test_create_menu_endpoint_with_right_permission_and_input(self):
        """Test for creation of new menu"""
        location = LocationFactory()
        menu = MenuFactory.build()
        main_meal_item = MealItemFactory.create()
        side_meal_item = MealItemFactory.create()
        protein_meal_item = MealItemFactory.create()

        vendor = VendorFactory.build()
        vendor_engagement = VendorEngagementFactory.build(vendor=vendor)
        vendor_engagement.save()

        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='create_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        data = {
            'date': menu.date.strftime('%Y-%m-%d'),
            'mealPeriod': menu.meal_period,
            'mainMealId': main_meal_item.id,
            'allowedSide': menu.allowed_side,
            'allowedProtein': menu.allowed_protein,
            'sideItems': [side_meal_item.id],
            'proteinItems': [protein_meal_item.id],
            'vendorEngagementId': vendor_engagement.id
        }
        headers = self.headers()
        headers.update({'X-Location': location.id})

        response = self.client().post(self.make_url('/admin/menus/'), \
                                      data=self.encode_to_json_string(data), headers=headers)
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))
        payload = response_json['payload']

        self.assertEqual(response.status_code, 201)
        self.assertJSONKeysPresent(payload, 'menu')
        self.assertJSONKeysPresent(payload['menu'], 'mainMeal', 'proteinItems',
                                   'sideItems', 'allowedProtein',
                                   'allowedSide', 'date', 'id', 'mealPeriod',
                                   'timestamps', 'vendorEngagementId')

        self.assertEqual(payload['menu']['vendorEngagementId'],
                         vendor_engagement.id)
        self.assertEqual(payload['menu']['mealPeriod'], menu.meal_period)
        self.assertEqual(payload['menu']['mainMealId'], main_meal_item.id)
        self.assertEqual(payload['menu']['allowedSide'], menu.allowed_side)
        self.assertEqual(payload['menu']['allowedProtein'],
                         menu.allowed_protein)
Beispiel #30
0
    def test_create_menu_endpoint_with_existing_main_meal_item(self):
        """Multiple menus with same same main meal id should not exist on the same day"""
        location = LocationFactory.create()
        main_meal_item = MealItemFactory.create(location=location)
        side_meal_item = MealItemFactory.create(location=location)
        protein_meal_item = MealItemFactory.create(location=location)

        headers = self.headers()
        headers.update({'X-Location': location.id})

        menu = MenuFactory.build(location=location)
        menu.save()
        vendor = VendorFactory.build(location=location)
        vendor_engagement = VendorEngagementFactory.build(vendor=vendor,
                                                          location=location)
        vendor_engagement.save()
        data = {
            'date': menu.date.strftime('%Y-%m-%d'),
            'mealPeriod': menu.meal_period,
            'mainMealId': main_meal_item.id,
            'allowedSide': menu.allowed_side,
            'allowedProtein': menu.allowed_protein,
            'sideItems': [side_meal_item.id],
            'proteinItems': [protein_meal_item.id],
            'vendorEngagementId': vendor_engagement.id,
            'location_id': location.id
        }

        existing_menu = MenuRepo().new_menu(
            menu.date.strftime('%Y-%m-%d'), menu.meal_period,
            main_meal_item.id, menu.allowed_side, menu.allowed_protein,
            [side_meal_item.id], [protein_meal_item.id], vendor_engagement.id,
            location.id)

        role = RoleFactory.create(name='admin')
        user_id = BaseTestCase.user_id()
        PermissionFactory.create(keyword='create_menu', role=role)
        UserRoleFactory.create(user_id=user_id, role=role)

        response = self.client().post(self.make_url('/admin/menus/'), \
                                      data=self.encode_to_json_string(data), headers=headers)
        response_json = self.decode_from_json_string(
            response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response_json['msg'],
            'You can\'t create multiple menus with same main item on the same day'
        )
Beispiel #31
0
 def create_location(self, point, name, user, default=False):
   print("Adding location " + name + " to " + user.username + "...", end="")
   location = get_object_or_None(Location, point=point, name=name, owner=user)
   if location:
     print("but already exists!", end="\n")
     return location
   else:
     location = LocationFactory.build(point=point,
                                      name=name,
                                      owner=user)
     location.clean()
     location.save()
     if default:
         user.get_profile().make_location_default(location)
     print("Success!", end="\n")
     return location