def test_session_authentication(admin_user): get_default_shop() client = APIClient() client.login(username=admin_user.username, password="******") response = client.get("/api/E-Commerce/order/") assert response.status_code == 200 client.logout() response = client.get("/api/E-Commerce/order/") assert response.status_code == 401
def initialize_front_browser_test(browser, live_server): activate("en") get_default_shop() url = live_server + "/" browser.visit(url) # set shop language to eng browser.find_by_id("language-changer").click() browser.find_by_xpath('//a[@class="language"]').first.click() return browser
def test_contact_detail_has_custom_toolbar_button(rf, admin_user): get_default_shop() contact = create_random_person(locale="en_US", minimum_name_comp_len=5) request = apply_request_middleware(rf.get("/"), user=admin_user) view_func = ContactDetailView.as_view() response = view_func(request, pk=contact.pk) content = force_text(response.render().content) assert "#mocktoolbarbutton" in content, 'custom toolbar button not found on detail page'
def test_url_uniqueness(rf): page = create_page(url='bacon', shop=get_default_shop()) with pytest.raises(ValidationError): page = create_page(url='bacon', shop=get_default_shop()) with transaction.atomic(): mpage = create_multilanguage_page(url="cheese", shop=get_default_shop()) with pytest.raises(ValidationError): mpage = create_multilanguage_page(url="cheese", shop=get_default_shop())
def test_form_part_for_new_group(rf, admin_user): get_default_shop() request = apply_request_middleware(rf.get("/"), user=admin_user) initialized_view = ContactGroupEditView(request=request, kwargs={"pk": None}) initialized_view.object = initialized_view.get_object() # Just for test form_def_values = initialized_view.get_form().form_defs.values() assert [form_def for form_def in form_def_values if form_def.name == "base"] # contact_group_sales_ranges should not be in form defs assert not [form_def for form_def in form_def_values if "contact_group_sales_ranges" in form_def.name]
def test_get_user(admin_user): get_default_shop() client = _get_client() client.force_authenticate(user=admin_user) response = client.get("/api/E-Commerce/front/user/me/") response_data = json.loads(response.content.decode("utf-8")) assert response.status_code == 200 assert "default_shipping_address" in response_data assert "first_name" in response_data
def test_future_page_not_visible(): today = now() page = create_page( available_from=(today + datetime.timedelta(days=1)), available_to=(today + datetime.timedelta(days=2)), shop=get_default_shop() ) assert not Page.objects.visible(get_default_shop()).filter(pk=page.pk).exists() assert not page.is_visible()
def test_basic_authentication(admin_user): get_default_shop() client = APIClient() client.credentials(HTTP_AUTHORIZATION='Basic ' + base64.b64encode(b'admin:password').decode("ascii")) response = client.get("/api/E-Commerce/order/") assert response.status_code == 200 client.credentials(HTTP_AUTHORIZATION='Basic ' + base64.b64encode(b'admin:bad-password').decode("ascii")) response = client.get("/api/E-Commerce/order/") assert response.status_code == 401
def get_request_with_basket(path="/", user=None, ajax=False): request = get_request(path, user) get_default_shop() # Create a Shop SessionMiddleware().process_request(request) MessageMiddleware().process_request(request) E-CommerceFrontMiddleware().process_request(request) request.session = {} if ajax: request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' return request
def test_login_fails_without_valid_password(client, regular_user, rf): prepare_user(regular_user) get_default_shop() client.post(reverse("E-Commerce:login"), data={ "username": regular_user.username, "password": "******" % REGULAR_USER_PASSWORD, }) request = rf.get("/") request.session = client.session assert get_user(request).is_anonymous(), "User is still anonymous"
def test_intra_request_user_changing(rf, regular_user): get_default_shop() # Create a shop mw = E-CommerceFrontMiddleware() request = apply_request_middleware(rf.get("/"), user=regular_user) mw.process_request(request) assert request.person == get_person_contact(regular_user) logout(request) assert request.user == AnonymousUser() assert request.person == AnonymousContact() assert request.customer == AnonymousContact()
def test_order_creator_customer_data(rf, admin_user): get_default_shop() contact = create_random_person(locale="en_US", minimum_name_comp_len=5) request = apply_request_middleware(rf.get("/", { "command": "customer_data", "id": contact.id }), user=admin_user) response = OrderEditView.as_view()(request) assert_contains(response, "name") assert_contains(response, contact.name)
def initialize_test(regular_user, person=True): client = SmartClient() get_default_shop() if person: contact = get_person_contact(regular_user) else: contact = get_company_contact(regular_user) client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) return client, contact
def test_api_permissions_authenticated_user(): users = [UserFactory(), UserFactory(), UserFactory()] my_user = users[-1] get_default_shop() viewset = UserViewSet() client = _get_client(my_user) permission_key = make_permission_config_key(viewset) # set API disabled config.set(None, permission_key, PermissionLevel.DISABLED) assert client.get("/api/E-Commerce/user/").status_code == status.HTTP_403_FORBIDDEN assert client.post("/api/E-Commerce/user/", {"email": "*****@*****.**"}).status_code == status.HTTP_403_FORBIDDEN # set API Public WRITE - access granted config.set(None, permission_key, PermissionLevel.PUBLIC_WRITE) response = client.get("/api/E-Commerce/user/") assert response.status_code == status.HTTP_200_OK user_data = sorted(json.loads(response.content.decode("utf-8")), key=lambda u: u["id"]) for ix, user in enumerate(user_data): assert users[ix].id == user["id"] # DELETE data too assert client.delete("/api/E-Commerce/user/%d/" % users[-1].id).status_code == status.HTTP_204_NO_CONTENT users.pop() # set API Public READ - access granted config.set(None, permission_key, PermissionLevel.PUBLIC_READ) response = client.get("/api/E-Commerce/user/") assert response.status_code == status.HTTP_200_OK user_data = sorted(json.loads(response.content.decode("utf-8")), key=lambda u: u["id"]) for ix, user in enumerate(user_data): assert users[ix].id == user["id"] # DELETE data - nope, not a safe method assert client.delete("/api/E-Commerce/user/%d/" % users[0].id).status_code == status.HTTP_403_FORBIDDEN # set API authenticated readonly - access only for readonly config.set(None, permission_key, PermissionLevel.AUTHENTICATED_READ) response = client.get("/api/E-Commerce/user/") assert response.status_code == status.HTTP_200_OK user_data = sorted(json.loads(response.content.decode("utf-8")), key=lambda u: u["id"]) for ix, user in enumerate(user_data): assert users[ix].id == user["id"] assert client.delete("/api/E-Commerce/user/%d/" % users[0].id).status_code == status.HTTP_403_FORBIDDEN # set API authenticated write - access granted config.set(None, permission_key, PermissionLevel.AUTHENTICATED_WRITE) assert client.get("/api/E-Commerce/user/").status_code == status.HTTP_200_OK assert client.delete("/api/E-Commerce/user/%d/" % users[-1].id).status_code == status.HTTP_204_NO_CONTENT users.pop() # set API admin only - not a chance config.set(None, permission_key, PermissionLevel.ADMIN) assert client.get("/api/E-Commerce/user/").status_code == status.HTTP_403_FORBIDDEN assert client.delete("/api/E-Commerce/user/%d/" % users[0].id).status_code == status.HTTP_403_FORBIDDEN
def test_edit_in_admin_url(rf): get_default_shop() soup = _get_front_soup(rf) _check_powered_by_href(soup, "https://E-Commerce.com") with override_settings(E-Commerce_FRONT_POWERED_BY_CONTENT='<p class="powered"><a href="123">456</a></p>'): soup = _get_front_soup(rf) _check_powered_by_href(soup, "123") with override_settings(E-Commerce_FRONT_POWERED_BY_CONTENT=None): soup = _get_front_soup(rf) assert soup.find("p", {"class": "powered"}) is None
def get_request(edit=False): get_default_shop() request = apply_request_middleware(RequestFactory().get("/")) request.session = {} if edit: request.user = SuperUser() set_edit_mode(request, True) assert is_edit_mode(request) else: request.user = AnonymousUser() return request
def test_weight_limits(): carrier = CustomCarrier.objects.create() sm = carrier.create_service( None, shop=get_default_shop(), enabled=True, tax_class=get_default_tax_class()) sm.behavior_components.add( WeightLimitsBehaviorComponent.objects.create( min_weight=100, max_weight=500)) source = BasketishOrderSource(get_default_shop()) assert any(ve.code == "min_weight" for ve in sm.get_unavailability_reasons(source)) source.add_line(type=OrderLineType.PRODUCT, weight=600) assert any(ve.code == "max_weight" for ve in sm.get_unavailability_reasons(source))
def test_refunds(browser, admin_user, live_server, settings): order = create_order_with_product( get_default_product(), get_default_supplier(), 10, decimal.Decimal("10"), n_lines=10, shop=get_default_shop()) order2 = create_order_with_product( get_default_product(), get_default_supplier(), 10, decimal.Decimal("10"), n_lines=10, shop=get_default_shop()) order2.create_payment(order2.taxful_total_price) initialize_admin_browser_test(browser, live_server, settings) _test_toolbar_visibility(browser, live_server, order) _test_create_full_refund(browser, live_server, order) _test_refund_view(browser, live_server, order2)
def test_multilanguage_page_404_no_xlate(rf): # https://github.com/edoburu/django-parler/issues/50 cache.clear() # this is here, because parler cache is enabled and tests use same pk with page page = create_multilanguage_page(eternal=True, url="no_content", shop=get_default_shop(), languages=("udm",)) # create page with udm language get_default_shop() request = apply_request_middleware(rf.get("/")) with translation.override("fi"): # change language of the page to fi view_func = PageView.as_view() with pytest.raises(Http404): response = view_func(request, url="no_content-udm") # Using Udmurt URL, but xlate is Finnish . . . assert response.status_code == 404 # ... should 404
def test_fetch(admin_user): activate("en") get_default_shop() group = get_default_customer_group() client = APIClient() client.force_authenticate(user=admin_user) response = client.get("/api/E-Commerce/contact_group/%s/" % group.pk) assert response.status_code == status.HTTP_200_OK contact_group_data = json.loads(response.content.decode("utf-8")) assert contact_group_data["id"] == group.id assert contact_group_data["translations"]["en"]["name"] == group.name
def test_get_by_pk(admin_user): get_default_shop() for i in range(0,10): UserFactory() user = UserFactory() client = _get_client(admin_user) response = client.get("/api/E-Commerce/user/%s/" % user.id) assert response.status_code == status.HTTP_200_OK user_data = json.loads(response.content.decode("utf-8")) assert user_data.get("id") == user.id assert user_data.get("username") == user.username
def test_get_by_pk(admin_user): get_default_shop() for i in range(0,10): create_random_person() contact = create_random_person() client = _get_client(admin_user) response = client.get("/api/E-Commerce/contact/%s/" % contact.id) assert response.status_code == status.HTTP_200_OK contact_data = json.loads(response.content.decode("utf-8")) assert contact_data.get("id") == contact.id assert contact_data.get("name") == contact.name
def test_fetch(admin_user): activate("en") get_default_shop() group = get_default_customer_group() price_display_option = group.price_display_options.first() client = APIClient() client.force_authenticate(user=admin_user) response = client.get("/api/E-Commerce/contact_group_price_display/%s/" % price_display_option.pk) assert response.status_code == status.HTTP_200_OK price_display_data = json.loads(response.content.decode("utf-8")) assert price_display_data["group"] == group.id
def test_tax_class_api(admin_user): get_default_shop() client = APIClient() client.force_authenticate(user=admin_user) tax_class_data = { "translations": { "en": {"name": "tax class 1"} }, "enabled": True } response = client.post("/api/E-Commerce/tax_class/", content_type="application/json", data=json.dumps(tax_class_data)) assert response.status_code == status.HTTP_201_CREATED tax_class = TaxClass.objects.first() assert tax_class.name == tax_class_data["translations"]["en"]["name"] assert tax_class.enabled == tax_class_data["enabled"] tax_class_data["translations"]["en"]["name"] = "Tax class 2" tax_class_data["enabled"] = False response = client.put("/api/E-Commerce/tax_class/%d/" % tax_class.id, content_type="application/json", data=json.dumps(tax_class_data)) assert response.status_code == status.HTTP_200_OK tax_class = TaxClass.objects.first() assert tax_class.name == tax_class_data["translations"]["en"]["name"] assert tax_class.enabled == tax_class_data["enabled"] response = client.get("/api/E-Commerce/tax_class/%d/" % tax_class.id) assert response.status_code == status.HTTP_200_OK data = json.loads(response.content.decode("utf-8")) assert tax_class.name == data["translations"]["en"]["name"] assert tax_class.enabled == tax_class_data["enabled"] response = client.get("/api/E-Commerce/tax_class/") assert response.status_code == status.HTTP_200_OK data = json.loads(response.content.decode("utf-8")) assert tax_class.name == data[0]["translations"]["en"]["name"] assert tax_class.enabled == data[0]["enabled"] response = client.delete("/api/E-Commerce/tax_class/%d/" % tax_class.id) assert response.status_code == status.HTTP_204_NO_CONTENT assert TaxClass.objects.count() == 0 tax_class = TaxClass.objects.create(name="class1") product = create_product("product1", tax_class=tax_class) # shouldn't be possible to delete a tax_class with a related product response = client.delete("/api/E-Commerce/tax_class/%d/" % tax_class.id) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "This object can not be deleted because it is referenced by" in response.content.decode("utf-8")
def test_update_product(admin_user): get_default_shop() product = create_product("test") client = _get_client(admin_user) data = _get_product_sample_data() response = client.put("/api/E-Commerce/product/%d/" % product.pk, content_type="application/json", data=json.dumps(data)) assert response.status_code == status.HTTP_200_OK # check whether the info was changed for lang in ("en", "pt-br"): activate(lang) product = Product.objects.first() _check_product_basic_data(product, data, lang)
def test_with_anonymous_user(): get_default_shop() # Create a shop mw = E-CommerceFrontMiddleware() request = get_unprocessed_request() mw.process_request(request) check_request_attribute_basics(request) assert isinstance(request.person, AnonymousContact) assert isinstance(request.customer, AnonymousContact) assert request.person == request.customer
def test_product_edit_view_with_params(rf, admin_user): get_default_shop() sku = "test-sku" name = "test name" request = apply_request_middleware(rf.get("/", {"name": name, "sku": sku}), user=admin_user) with replace_modules([CategoryModule, ImportAdminModule, ProductModule, MediaModule, ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]): with admin_only_urls(): view_func = ProductEditView.as_view() response = view_func(request) assert (sku in response.rendered_content) # it's probable the SKU is there assert (name in response.rendered_content) # it's probable the name is there
def test_product_module_search(rf, admin_user): get_default_shop() request = apply_request_middleware(rf.get("/"), user=admin_user) with replace_modules([CategoryModule, ImportAdminModule, ProductModule, MediaModule, ProductTypeModule, ManufacturerModule, PaymentMethodModule, ShippingMethodModule]): with admin_only_urls(): default_product = get_default_product() model_url = get_model_url(default_product, shop=get_shop(request)) sku = default_product.sku assert any(sr.url == model_url for sr in get_search_results(request, query=sku)) # Queries work assert any(sr.is_action for sr in get_search_results(request, query=sku[:5])) # Actions work assert empty_iterable(get_search_results(request, query=sku[:2])) # Short queries don't
def test_contact_detail_has_mocked_toolbar_action_items(rf, admin_user): get_default_shop() contact = create_random_person(locale="en_US", minimum_name_comp_len=5) request = apply_request_middleware(rf.get("/"), user=admin_user) view_func = ContactDetailView.as_view() with override_provides("admin_contact_toolbar_action_item", [ "E-Commerce.testing.modules.mocker.toolbar:MockContactToolbarActionItem" ]): assert _check_if_mock_action_item_exists(view_func, request, contact) with override_provides("admin_contact_toolbar_action_item", []): assert not _check_if_mock_action_item_exists(view_func, request, contact)
def test_multishop_edit_view(rf, admin_user): get_default_shop() request = apply_request_middleware(rf.get("/"), user=admin_user) view = ShopEditView(request=request, kwargs={"pk": None}) with override_settings(E-Commerce_ENABLE_MULTIPLE_SHOPS=False): with pytest.raises(Problem): view.get_object() # Now view object should throw Problem with override_settings(E-Commerce_ENABLE_MULTIPLE_SHOPS=True): new_shop = view.get_object() assert new_shop.pk is None