def pytest_configure(config): from wapps import factories register(factories.CategoryFactory) register(factories.FullIdentityFactory, 'full_identity', site=LazyFixture('site')) register(factories.IdentityFactory, 'identity', site=LazyFixture('site')) register(factories.ImageFactory) register(factories.ImageFactory, 'image') register(factories.PageFactory) register(factories.SiteFactory) register(factories.UserFactory) register(factories.TagFactory)
class FunctionCallFactory(DFFactory): class Meta: model = FunctionCall spark_session = LazyFixture("spark_session") df: DataFrame() other_df: DataFrame(schema=["id", "key", "value"])
class DataFrameFactory(factory.Factory): class Meta: model = DataFrame spark_session = LazyFixture("spark_session") data = None schema = None @classmethod def _create(self, model_class, spark_session, data, schema): return spark_session.createDataframe(data, schema)
from cesium_app import models from cesium_app.tests.fixtures import (TMP_DIR, ProjectFactory, DatasetFactory, FeaturesetFactory, ModelFactory, PredictionFactory) print('Loading test configuration from test_config.yaml') basedir = pathlib.Path(os.path.dirname(__file__)) / '../..' cfg = load_config([basedir / 'test_config.yaml']) set_server_url(f'http://*****:*****@pytest.fixture(scope='session', autouse=True) def delete_temporary_files(request): def teardown(): shutil.rmtree(TMP_DIR, ignore_errors=True) request.addfinalizer(teardown) register(ProjectFactory) register(DatasetFactory) register(DatasetFactory, "unlabeled_dataset", name="unlabeled") register(FeaturesetFactory) register(ModelFactory) register(PredictionFactory) register(PredictionFactory, "unlabeled_prediction", dataset=LazyFixture("unlabeled_dataset"))
import pytest from pynamodb_factoryboy import __version__ from pytest_factoryboy import register, LazyFixture from .factories import TestFactory from .models import TestModel register(TestFactory) def test_simple(test_model): assert TestModel.count() == 1 assert isinstance(test_model.unicode_attr, str) assert isinstance(test_model.binary_attr, bytes) assert isinstance(test_model.binary_set_attr, set) assert isinstance(test_model.boolean_attr, bool) @pytest.mark.parametrize('value', ['asdf']) @pytest.mark.parametrize('test_model__unicode_attr', [ LazyFixture(lambda value: value), ]) def test_attributes_as_fixtures(test_model, value): assert test_model.unicode_attr == value
resp = reg_client.post(url, data=dict(note='test note', service_date=service.date_to_str, categories=cat, servants=servants), follow=True) assert resp.status_code == 200 export_to_html(resp, 'create_services_view_by_reg_user.html') # asserts # for ser in servants: # assert str2bytes(ser.name) in resp.content # assert str2bytes(cat.name) in resp.content @pytest.mark.django_db @pytest.mark.parametrize("service__servants", [LazyFixture("default_user")]) @pytest.mark.parametrize("service__categories", [(LazyFixture("default_category"))]) def test_detail_service_view(auto_login_user, service): service_slug = service.slug servants = service.servant_names client, user = auto_login_user() # create auto logon user url = reverse('service_detail', kwargs={'slug': service_slug}) resp = client.get(url) assert resp.status_code == 200 export_to_html(resp, 'detail_service_view.html') # asserts assert str2bytes(service.category_names) in resp.content assert str2bytes(service.note) in resp.content
class UserFactory(factory.Factory): """User factory.""" class Meta: model = User username = factory.faker.Faker("user_name") password = factory.faker.Faker("password") is_active = factory.LazyAttribute(lambda f: f.password == "ok") register(UserFactory) register( UserFactory, "partial_user", password=LazyFixture("ok_password"), ) @pytest.fixture def ok_password(): return "ok" @pytest.mark.parametrize("user__password", [LazyFixture("ok_password")]) def test_lazy_attribute(user): """Test LazyFixture value is extracted before the LazyAttribute is called.""" assert user.is_active def test_lazy_attribute_partial(partial_user):
_string_hash = factory.SubFactory(StringHashFactory) @classmethod def _create(cls, model_class, *args, **kwargs): obj = model_class() obj._string_hash = kwargs.get('_string_hash') return obj register(UserFactory, 'user') register(UserFactory, 'another_user') register(EndpointFactory, 'endpoint') register(RequestFactory, 'request_1') # unfortunately, we can't use fixture name: 'request' register(RequestFactory, 'request_2') register(OutlierFactory, 'outlier_1', request=LazyFixture('request_1')) register(OutlierFactory, 'outlier_2', request=LazyFixture('request_2')) register(CodeLineFactory, 'code_line') register(StackLineFactory, 'stack_line', request=LazyFixture('request_1')) register(StackLineFactory, 'stack_line_2', request=LazyFixture('request_2'), indent=1) register(CustomGraphFactory, 'custom_graph') register(CustomGraphDataFactory, 'custom_graph_data') register(GroupedStackLineFactory, 'grouped_stack_line') register(StringHashFactory, 'string_hash') register(PathHashFactory, 'path_hash')
import pytest from pytest_factoryboy import LazyFixture from wapps.blog.models import Blog, BlogPost from wapps.pytest import assert_can_create_at, assert_can_not_create_at from wapps.pytest import assert_allowed_subpage_types, assert_allowed_parent_types @pytest.mark.django_db def test_blog_hierarchy_restrictions(blog, site): assert_allowed_subpage_types(blog, [BlogPost]) assert_can_create_at(site.root_page.__class__, Blog) assert_can_not_create_at(BlogPost, Blog) @pytest.mark.django_db def test_blogpost_hierarchy_restrictions(blog_post, site): assert_allowed_parent_types(blog_post, [Blog]) assert_can_not_create_at(site.root_page.__class__, BlogPost) assert_can_create_at(Blog, BlogPost) @pytest.mark.django_db @pytest.mark.parametrize('blog_post__parent', [LazyFixture('blog')]) def test_blogpost_parent_blog(blog, blog_post): assert isinstance(blog_post.blog, Blog) assert blog_post.blog == blog
"content": new_content }, ) assert result.get("errors") is None assert "id" not in result["data"]["updateComment"] assert "content" not in result["data"]["updateComment"] assert result["data"]["updateComment"]["reason"] == "UNAUTHORIZED" assert comment_fetcher.fetch( comment.id).content != new_content # type: ignore @pytest.mark.parametrize( "comment__author", [LazyFixture(lambda user_factory: user_factory.create()) ], # ensure post and comment have different authors ) def test_update_comment_requires_auth_from_creating_user( client: GraphQLClient, comment_factory: Type[CommentFactory], comment_fetcher: Fetcher[Comment], comment: FakeComment, ): """Check that updating a comment as another user returns AuthError.""" new_content = comment_factory.build().content result = client.execute( """ mutation updateComment($commentId: Int!, $content: String!) { updateComment(id: $commentId, content: $content) { ... on AuthError {
import pytest from pytest_factoryboy import register, LazyFixture from .factories import CategoryFactory, LevelFactory, ThemeFactory, WordFactory register(CategoryFactory) register(CategoryFactory, "other_category") register(LevelFactory) register(LevelFactory, "other_level") register(ThemeFactory, category=LazyFixture("category"), level=LazyFixture("level")) register(ThemeFactory, "theme_other_category", category=LazyFixture("other_category"), level=LazyFixture("level")) register(ThemeFactory, "theme_other_level", category=LazyFixture("category"), level=LazyFixture("other_level")) register(ThemeFactory, "theme_other_category_level", category=LazyFixture("other_category"), level=LazyFixture("other_level")) register(WordFactory, theme=LazyFixture("theme")) @pytest.fixture def api_client(): from rest_framework.test import APIClient return APIClient()
from tests.factories.game import GameFactory from tests.factories.game_event import GameEventFactory from tests.factories.game_request import GameRequestFactory from tests.factories.move import MoveFactory from tests.factories.player import PlayerFactory register(GameEventFactory) register(GameRequestFactory) register(MoveFactory) register(PlayerFactory) register(PlayerFactory, "player1", username="******") register(PlayerFactory, "player2", username="******") register( GameFactory, slug="ABC123", player1=LazyFixture("player1"), player2=LazyFixture("player2"), ) # Utilities @pytest.fixture def api_client(player): return APIClient() @pytest.fixture def call_api(api_client): def wrapped(http_method, url, user=None, payload=None): if user:
import pytest from pytest_factoryboy import LazyFixture @pytest.mark.django_db def test_risk(risk): assert risk.name == 'Vehicle' @pytest.mark.django_db @pytest.mark.parametrize('risk_field__risk', [LazyFixture('risk')]) def test_risk_field(risk_field, risk): assert risk_field.risk.id == risk.id @pytest.mark.django_db @pytest.mark.parametrize('field_option__field', [LazyFixture('risk_field')]) def test_field_option(field_option, risk_field): assert field_option.field.id == risk_field.id
import pytest from pytest_factoryboy import LazyFixture from wapps.gallery.models import Gallery @pytest.mark.django_db @pytest.mark.parametrize('album__parent', [LazyFixture('gallery')]) def test_album_parent_gallery(gallery, album): assert isinstance(album.gallery, Gallery) assert album.gallery == gallery @pytest.mark.django_db def test_root_album_has_no_parent_gallery(album): assert album.gallery is None
# you will need to ensure that it is tested against both # SqlLite and PostgresSQL # adding load_env() to settings.py will enable Postgress access # # ------------------ IMPORTANT ------------------- LIST_URL = 'api:food-list' DETAIL_URL = 'api:food-detail' MOVE_URL = 'api:food-move' MERGE_URL = 'api:food-merge' if (Food.node_order_by): node_location = 'sorted-child' else: node_location = 'last-child' register(FoodFactory, 'obj_1', space=LazyFixture('space_1')) register(FoodFactory, 'obj_2', space=LazyFixture('space_1')) register(FoodFactory, 'obj_3', space=LazyFixture('space_2')) register(SupermarketCategoryFactory, 'cat_1', space=LazyFixture('space_1')) # @pytest.fixture # def true(): # return True @pytest.fixture def false(): return False @pytest.fixture
"""Test factory registration with specific name.""" assert author != second_author assert second_author.name == "Mr. Hyde" register(AuthorFactory, "partial_author", name="John Doe") def test_partial(partial_author): """Test fixture partial specialization.""" assert partial_author.name == "John Doe" register(AuthorFactory, "another_author", name=LazyFixture(lambda: "Another Author")) @pytest.mark.parametrize("book__author", [LazyFixture("another_author")]) def test_lazy_fixture_name(book, another_author): """Test that book author is replaced with another author by fixture name.""" assert book.author == another_author assert book.author.name == "Another Author" @pytest.mark.parametrize("book__author", [LazyFixture(lambda another_author: another_author)]) def test_lazy_fixture_callable(book, another_author): """Test that book author is replaced with another author by callable.""" assert book.author == another_author assert book.author.name == "Another Author"
"""Test post generation declaration.""" assert author.user.username == "admin" assert author.user.is_active is True register(AuthorFactory, "second_author") @pytest.mark.parametrize("second_author__name", ["Mr. Hyde"]) def test_second_author(author, second_author): """Test factory registration with specific name.""" assert author != second_author assert second_author.name == "Mr. Hyde" register(AuthorFactory, "partial_author", name="John Doe", register_user=LazyFixture(lambda: "*****@*****.**")) def test_partial(partial_author): """Test fixture partial specialization.""" assert partial_author.name == "John Doe" assert partial_author.user.username == "*****@*****.**" register(AuthorFactory, "another_author", name=LazyFixture(lambda: "Another Author")) @pytest.mark.parametrize("book__author", [LazyFixture("another_author")]) def test_lazy_fixture_name(book, another_author): """Test that book author is replaced with another author by fixture name.""" assert book.author == another_author