import pytest_factoryboy from schemacms.projects.tests import factories as p_factories from schemacms.datasources.tests import factories as ds_factories from schemacms.states.tests import factories as st_factories from schemacms.users.tests import factories as u_factories from schemacms.pages.tests import factories as pages_factories from schemacms.tags.tests import factories as tags_factories pytest_factoryboy.register(u_factories.UserFactory) pytest_factoryboy.register(p_factories.ProjectFactory, "project") pytest_factoryboy.register(ds_factories.DataSourceFactory) pytest_factoryboy.register(ds_factories.DescriptionFactory, "ds_description") pytest_factoryboy.register(ds_factories.DataSourceMetaFactory) pytest_factoryboy.register(ds_factories.ScriptFactory, "script") pytest_factoryboy.register(ds_factories.JobFactory, "job") pytest_factoryboy.register(ds_factories.JobMetaFactory) pytest_factoryboy.register(ds_factories.JobStepFactory, "step") pytest_factoryboy.register(ds_factories.FilterFactory, "filter_") pytest_factoryboy.register(st_factories.StateFactory, "state") pytest_factoryboy.register(st_factories.StateTagFactory, "state_tag") pytest_factoryboy.register(pages_factories.BlockTemplateFactory, "block_template") pytest_factoryboy.register(pages_factories.PageTemplateFactory, "page_template") pytest_factoryboy.register(pages_factories.BlockTemplateElementFactory, "block_template_element") pytest_factoryboy.register(pages_factories.PageBlockFactory, "page_block") pytest_factoryboy.register(pages_factories.PageBlockObservableElementFactory, "observable_element") pytest_factoryboy.register(pages_factories.CustomElementSetFactory,
import pytest from pytest_factoryboy import register from project.country.models import City, Country from project.country.tests.factories import CountryFactory from project.graphql.query import CountryType from project.graphql.utils import CustomNode register(CountryFactory, "country_1") @pytest.mark.usefixtures("client_query") @pytest.mark.django_db def test_create_country(client_query, faker): query = """ mutation($name:String!, $population: Int!){ createCountry(name: $name, population: $population){ country{ id } } } """ variables = { "name": faker.pystr(), "population": faker.pyint(), } response = client_query(query, variables=variables) content = response.json() country_node_id = content["data"]["createCountry"]["country"]["id"] (
EmbargoedAssetBlobFactory, EmbargoedUploadFactory, PublishedAssetFactory, PublishedVersionFactory, SocialAccountFactory, UploadFactory, UserFactory, ZarrArchiveFactory, ZarrUploadFileFactory, ) if TYPE_CHECKING: # mypy_boto3_s3 only provides types import mypy_boto3_s3 as s3 register(PublishedAssetFactory, _name='published_asset') register(DraftAssetFactory, _name='draft_asset') register(AssetBlobFactory) register(EmbargoedAssetBlobFactory) register(DandisetFactory) register(EmbargoedAssetBlobFactory) register(EmbargoedUploadFactory) register(PublishedVersionFactory, _name='published_version') register(DraftVersionFactory, _name='draft_version') # registering DraftVersionFactory after PublishedVersionFactory means # the fixture `version` will always be a draft register(UserFactory) register(SocialAccountFactory) register(UploadFactory) register(ZarrArchiveFactory) register(ZarrUploadFileFactory)
import hamsterlib import pytest from click.testing import CliRunner from pytest_factoryboy import register import hamster_cli.hamster_cli as hamster_cli from . import factories try: from configparser import SafeConfigParser except: from ConfigParser import SafeConfigParser register(factories.CategoryFactory) register(factories.ActivityFactory) register(factories.FactFactory) @pytest.fixture def runner(): """Used for integrations tests.""" def runner(args=[]): return CliRunner().invoke(hamster_cli.run, args) return runner @pytest.fixture def base_config(): """Provide a generic baseline configuration."""
import pytest import betamax import os import json from datetime import datetime from webhookdb import create_app, db from webhookdb.oauth import GithubSession from webhookdb.tasks.fetch import github from flask.testing import FlaskClient from factories import ( UserFactory, RepoFactory, MilestoneFactory, PullRequestFactory ) from pytest_factoryboy import register register(UserFactory) register(RepoFactory) register(MilestoneFactory) register(PullRequestFactory) record_mode = 'none' if os.environ.get("CI") else 'once' with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' config.default_cassette_options['record_mode'] = record_mode class GitHubJSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime):
import fakeredis import pytest import responses from flask.wrappers import Response from pytest_factoryboy import register from werkzeug.utils import cached_property from devlog import config_test, make_app from devlog.assets import all_css from devlog.models import MODELS, db from .factories import ( LinkFactory, PostFactory, QuipFactory, TagFactory, TaggedPostFactory, UserFactory, ) register(TagFactory) register(PostFactory) register(TaggedPostFactory) register(LinkFactory) register(UserFactory) register(QuipFactory) class TestResponse(Response): @cached_property def text(self): if self.mimetype.startswith('text'): return self.data.decode(self.charset) return self.data
import os import pytest from config import configs from peewee_migrate import Router from pytest_factoryboy import register from tilda import create_app from .factories import AdminFactory, RoleFactory, UserFactory register(UserFactory) register(AdminFactory) register(RoleFactory) @pytest.fixture def app(): flask_app = create_app(configs['testing']) router = Router(flask_app.db.database) router.run() yield flask_app flask_app.db.close_db('') current_path = os.path.dirname(__file__) os.remove('{}/../test.db'.format(current_path))
from pytest_factoryboy import register from tests.apps.fakeprojects import factories as fprojects_factories from tests.comments import factories as comment_factories from tests.reports import factories register(fprojects_factories.FakeProjectContentFactory) register(comment_factories.CommentFactory) register(factories.ReportFactory)
import pytest from pytest_factoryboy import register from rest_framework.test import APIClient, APIRequestFactory from factories import ( UserFactory, EmailAddressFactory, EmailAddressVerificationFactory, ) @pytest.fixture def api_request(): return APIRequestFactory().request() @pytest.fixture def api_client(): return APIClient() register(UserFactory) register(EmailAddressFactory) register(EmailAddressVerificationFactory)
def _create(cls, model_class, foo): assert foo.value == foo.expected return super(BarFactory, cls)._create(model_class, foo=foo) class Meta: model = Bar def test_invocation_order(foo): """Test that post-generation hooks are done and the value is 2.""" assert foo.value == 2 register( BarFactory, 'depends_on_1', _postgen_dependencies=["foo__set1"], ) """Forces 'set1' to be evaluated first.""" register( BarFactory, 'depends_on_2', _postgen_dependencies=["foo__set2"], ) """Forces 'set2' to be evaluated first.""" @pytest.mark.parametrize('foo__value', [3]) @pytest.mark.parametrize('foo__expected', [1])
author = factory.SubFactory(AuthorFactory) book_edition = factory.RelatedFactory("tests.test_factory_fixtures.EditionFactory", "book") class EditionFactory(factory.Factory): """Book edition factory.""" class Meta: model = Edition book = factory.SubFactory(BookFactory) year = 1999 register(BookFactory) register(EditionFactory) def test_factory(book_factory): """Test model factory fixture.""" assert book_factory == BookFactory def test_model(book): """Test model fixture.""" assert book.name == "Alice in Wonderland" assert book.price == 3.99 assert book.author.name == "Charles Dickens" assert book.author.user is None assert book.editions[0].year == 1999
import pytest from pytest_factoryboy import register from example.factories import BlogFactory, AuthorFactory, AuthorBioFactory, EntryFactory, CommentFactory, \ TaggedItemFactory register(BlogFactory) register(AuthorFactory) register(AuthorBioFactory) register(EntryFactory) register(CommentFactory) register(TaggedItemFactory) @pytest.fixture def single_entry(blog, author, entry_factory, comment_factory, tagged_item_factory): entry = entry_factory(blog=blog, authors=(author,)) comment_factory(entry=entry) tagged_item_factory(content_object=entry) return entry @pytest.fixture def multiple_entries(blog_factory, author_factory, entry_factory, comment_factory): entries = [ entry_factory(blog=blog_factory(), authors=(author_factory(),)), entry_factory(blog=blog_factory(), authors=(author_factory(),)), ] comment_factory(entry=entries[0])
def test_abstract(): with pytest.raises(AssertionError): register(AbstractFactory)
def test_without_model(): """Test that factory without model can't be registered.""" with pytest.raises(AssertionError): register(WithoutModelFactory)
import pytest from pytest_factoryboy import register from tests.businesses.factories import ProductFactory from .factories import AffiliatedPersonFactory, OrganizationFactory register(AffiliatedPersonFactory) register(OrganizationFactory) register(ProductFactory)
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
from pytest import fixture from tests.factories.meal import IngredientFactory, MealFactory from pytest_factoryboy import register from tests.factories.user import UserFactory register(UserFactory) register(IngredientFactory) register(MealFactory) @fixture def meal_tree(meal_factory): parent_meal = meal_factory.create(ingredient=None) meal_factory.create_batch(3, parent=parent_meal) return parent_meal
from pytest_factoryboy import register from tests.ideas import factories as idea_factories from tests.journeys import factories as journey_factories register(idea_factories.IdeaFactory) register(journey_factories.JourneyEntryFactory)
import pytest from pytest_factoryboy import register from rest_auth.app_settings import create_token, TokenSerializer from rest_auth.models import TokenModel from apps.users.factories import UserFactory register(UserFactory, 'user') @pytest.fixture def user_dict(): return { 'username': '******', 'email': '*****@*****.**', 'password': '******', 'first_name': 'Bot', 'last_name': 'Botovich' } @pytest.fixture def token(user): return create_token(TokenModel, user, TokenSerializer)
# Discover factories to automatically register them to pytest-factoryboy and to # override its session enabled_factories = [] for attr_name in dir(factories): obj = getattr(factories, attr_name) if not inspect.isclass(obj): continue if not issubclass(obj, Factory): continue if obj._meta.model is None: # It is an abstract class continue enabled_factories.append(obj) for factory in enabled_factories: register(factory) register(factories.WorkspaceFactory, "second_workspace") class CustomClient(FlaskClient): def open(self, *args, **kwargs): if kwargs.pop('use_json_data', True) and 'data' in kwargs: # JSON-encode data by default kwargs['data'] = json.dumps(kwargs['data']) kwargs['headers'] = kwargs.get('headers', []) + [ ('Content-Type', 'application/json'), ] # Reset queries to make the log_queries_count from flask import _app_ctx_stack
self.password = password self.is_active = is_active 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 register_module(module): for name, obj in inspect.getmembers(module): if isinstance(obj, FactoryMetaClass) and not obj._meta.abstract: register(obj)
# Discover factories to automatically register them to pytest-factoryboy and to # override its session enabled_factories = [] for attr_name in dir(factories): obj = getattr(factories, attr_name) if not inspect.isclass(obj): continue if not issubclass(obj, Factory): continue if obj._meta.model is None: # It is an abstract class continue enabled_factories.append(obj) for factory in enabled_factories: register(factory) register(factories.WorkspaceFactory, "second_workspace") class CustomClient(FlaskClient): def open(self, *args, **kwargs): if kwargs.pop('use_json_data', True) and 'data' in kwargs: # JSON-encode data by default kwargs['data'] = json.dumps(kwargs['data']) kwargs['headers'] = kwargs.get('headers', []) + [ ('Content-Type', 'application/json'), ] # Reset queries to make the log_queries_count
from rest_framework.test import APIClient from .factories import ( ApproachFactory, ChallengeFactory, SubmissionFactory, TaskFactory, TeamFactory, UserFactory, ) @pytest.fixture def api_client() -> APIClient: return APIClient() @pytest.fixture def authenticated_api_client(user) -> APIClient: client = APIClient() client.force_authenticate(user=user) return client register(ApproachFactory) register(ChallengeFactory) register(SubmissionFactory) register(TaskFactory) register(TeamFactory) register(UserFactory)
from pytest_factoryboy import register from wapps.gallery import factories register(factories.GalleryFactory) register(factories.AlbumFactory) register(factories.ManualAlbumFactory)
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"))
from flask.wrappers import Response from pytest_factoryboy import register from werkzeug.utils import cached_property from bip import make_app from bip.models import Attachment, ChangeRecord, Label, Page, PageLabel, User, db from .factories import ( AttachmentFactory, LabelFactory, PageFactory, PageLabelFactory, UserFactory, ) register(PageFactory) register(UserFactory) register(LabelFactory) register(PageLabelFactory) register(AttachmentFactory) class TestResponse(Response): @cached_property def text(self): if self.mimetype.startswith('text'): return self.data.decode(self.charset) return self.data def fake_gen_password_hash(password):
import pytest from pytest_factoryboy import register from app1.tests.factories import UserFactory, CategoryFactory, ProductFactory # access the fixture using: user_factory register(UserFactory) # access the fixture using: user_factory register(CategoryFactory) # access the fixture using: user_factory register(ProductFactory) @pytest.fixture def new_user1(db, user_factory): user = user_factory.create() return user @pytest.fixture def new_category(db, category_factory): category = category_factory.create() return category @pytest.fixture def new_product(db, product_factory): product = product_factory.create() return product
@pytest.fixture(scope="session", autouse=True) def set_mail_backend(): settings.SAASY_API_KEY = "some_test_key" settings.EMAIL_BACKEND = "apps.core.custom_email_backend.CustomEmailBackend" @pytest.fixture() def logged_in_client(user, client): response = client.post(GENERATE_CODE_URL, { "email": user.email, "password": TEST_PASSWORD }) assert response.status_code == 200 client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {response.data['access']}" return client @pytest.fixture(scope="session", autouse=True) def remove_tempdir(request): """ This fixture remove temporary directory created for the media root """ def fin(): if all([os.path.isdir(settings.MEDIA_ROOT), "test" == settings.ENV]): shutil.rmtree(settings.MEDIA_ROOT) request.addfinalizer(fin) register(UserFactory, email=TEST_EMAIL)
import pytest from pytest_factoryboy import register from parkings.factories import (AdminUserFactory, OperatorFactory, ParkingAreaFactory, ParkingFactory, StaffUserFactory, UserFactory) register(OperatorFactory) register(ParkingFactory) register(AdminUserFactory, 'admin_user') register(StaffUserFactory, 'staff_user') register(UserFactory) register(ParkingAreaFactory) @pytest.fixture(autouse=True) def set_faker_random_seed(): from parkings.factories.faker import fake fake.seed(777)
from pytest_factoryboy import register from meinberlin.test.factories import offlineevents register(offlineevents.OfflineEventFactory)
import pytest from pytest_factoryboy import register from rest_framework.test import APIClient from example.factories import (ArtProjectFactory, AuthorBioFactory, AuthorBioMetadataFactory, AuthorFactory, AuthorTypeFactory, BlogFactory, CommentFactory, CompanyFactory, EntryFactory, ResearchProjectFactory, TaggedItemFactory) register(BlogFactory) register(AuthorFactory) register(AuthorBioFactory) register(AuthorBioMetadataFactory) register(AuthorTypeFactory) register(EntryFactory) register(CommentFactory) register(TaggedItemFactory) register(ArtProjectFactory) register(ResearchProjectFactory) register(CompanyFactory) @pytest.fixture def single_entry(blog, author, entry_factory, comment_factory, tagged_item_factory): entry = entry_factory(blog=blog, authors=(author, )) comment_factory(entry=entry) tagged_item_factory(content_object=entry) return entry
import pytest import json from pytest_factoryboy import register from .factories import PersonFactory, PetFactory, UserFactory register(PersonFactory) register(PetFactory) register(UserFactory) @pytest.fixture def customer_client(db): from django.test.client import Client return Client() @pytest.fixture def create_token(customer_client): user = UserFactory.create() response_auth = customer_client.post('/api/v1/auth', data={ 'username': user.username, 'password': '******' }) content_auth = json.loads(response_auth.content.decode()) return content_auth["access"]
# -*- encoding: utf-8 -*- """Fixtures that are of general use.""" from __future__ import unicode_literals import datetime import faker as faker_ import pytest from hamster_lib.lib import HamsterControl from hamster_lib.storage import BaseStore from pytest_factoryboy import register from . import factories register(factories.CategoryFactory) register(factories.ActivityFactory) register(factories.TagFactory) register(factories.FactFactory) faker = faker_.Faker() def convert_time_to_datetime(time_string): """ Helper method. If given a %H:%M string, return a datetime.datetime object with todays date. """ return datetime.datetime.combine(
import pytest from graphene.test import Client from pytest_factoryboy import register from server.api.internal.schema import schema from server.tests.factories import ShortURLFactory for factory in (ShortURLFactory, ): register(factory) @pytest.fixture def gql_client(): return Client(schema=schema)
from pytest_factoryboy import register from tests.offlinephases import factories as offlinephase_factories register(offlinephase_factories.OfflinephaseFactory)
import json import pytest from dotenv import load_dotenv from StockMarketApi.models import User from StockMarketApi.app import create_app from StockMarketApi.extensions import db as _db from pytest_factoryboy import register from tests.factories import UserFactory register(UserFactory) @pytest.fixture(scope="session") def app(): load_dotenv(".testenv") app = create_app(testing=True) return app @pytest.fixture def db(app): _db.app = app with app.app_context(): _db.create_all() yield _db _db.session.close() _db.drop_all()
import pytest from pytest_factoryboy import register from vbb_backend.program.tests.factories import SlotFactory, ComputerFactory from vbb_backend.users.tests.factories import * """ This conf file is used by all modules. Only add fixtures that span multiple modules. """ @pytest.fixture(autouse=True) def media_storage(settings, tmpdir): settings.MEDIA_ROOT = tmpdir.strpath @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass register(SlotFactory) register(ComputerFactory) register(MentorFactory) register(StudentFactory) register(TeacherFactory) register(HeadmasterFactory) register(ProgramManagerFactory) register(ProgramDirectorFactory)
from __future__ import print_function, division, absolute_import import factory import inspect import pytest from pytest_factoryboy import register from ..conftest import determine_scope from . import factories # register all xxxFactory classes # # pytest_factoryboy @register decorator registers fixtures in directory where it is # called. To make available to tests, need to either import them into conftest or register # manually in conftest. The below code registers them manually instead of with # @register class decorator. For docs on pytest_factoryboy, # see https://pytest-factoryboy.readthedocs.io/en/latest for item in dir(factories): attr = getattr(factories, item) if inspect.isclass(attr) and issubclass(attr, factory.Factory): register(attr) @pytest.fixture(scope=determine_scope, autouse=True) def session(database): ''' SQLA session fixture. set autouse=True to ensure persistence ''' session = database.Session() session.begin() yield session session.rollback() session.close()
from pytest_factoryboy import register from . import factories as document_factories register(document_factories.ChapterFactory) register(document_factories.ParagraphFactory)
from pytest_factoryboy import register from tests.apps.fakeprojects import factories as fprojects_factories from tests.ratings import factories as rating_factories import factories as comment_factories register(fprojects_factories.FakeProjectContentFactory) register(rating_factories.RatingFactory) register(comment_factories.CommentFactory)
""" Functions that aids writing unit tests. """ import pytest import pytest_selenium as _ from sulfur import Driver as _sulfur_driver import pytest_django as _ from pytest_factoryboy import register from django.forms import model_to_dict from codeschool.factories import UserFactory, fake # Factory boy fixtures register(UserFactory) # Regular Fixtures @pytest.fixture def password(): return fake.password() @pytest.fixture def user_with_password(password): """Create user with password""" user = UserFactory.create() user.set_password(password) user.save() return user
from pytest_factoryboy import register from tests.comments import factories as comment_factories from tests.documents import factories as document_fatories register(comment_factories.CommentFactory) register(document_fatories.DocumentFactory) register(document_fatories.ParagraphFactory)
""" Define pytest configuration and setup. The urls import is needed to make sure all urls/subclasses are registered BEFORE fixtures run. """ from django.urls import clear_script_prefix, set_script_prefix import pytest from pytest_factoryboy import register from rest_framework.test import APIClient from testapp import urls # noqa from testapp.factories import GroupFactory, HobbyFactory, PersonFactory register(PersonFactory, "person") register(HobbyFactory) register(GroupFactory) @pytest.fixture def api_client(): client = APIClient() return client @pytest.fixture def script_path(request): set_script_prefix("/some-prefix") request.addfinalizer(clear_script_prefix)
@register class PatronymicFactory(factory.django.DjangoModelFactory): name = factory.LazyAttributeSequence(lambda s, x: f'{faker.name()}{x}') class Meta: model = Patronymic @register class SurnameFactory(factory.django.DjangoModelFactory): name = factory.LazyAttributeSequence(lambda s, x: f'{faker.last_name()}{x}') class Meta: model = Surname class EmployeeFactory(factory.django.DjangoModelFactory): surname = factory.SubFactory(SurnameFactory) firstname = factory.SubFactory(FirstNameFactory) patronymic = factory.SubFactory(PatronymicFactory) boss = factory.SubFactory('employees.tests.conftest.EmployeeFactory') class Meta: model = Employee register(EmployeeFactory)
from django.test import RequestFactory import pytest from published.constants import NEVER_AVAILABLE from pytest_factoryboy import register from foxtail_blog.tests.factories import PostFactory register(PostFactory, "post") register(PostFactory, "second_post") register(PostFactory, "hidden_post", publish_status=NEVER_AVAILABLE) @pytest.fixture def request_factory() -> RequestFactory: return RequestFactory()
from pytest_factoryboy import register import factory import pytest class EmptyModel(object): pass class AttributesFactory(factory.Factory): class Meta: model = EmptyModel attributes = None register(AttributesFactory, "with_attributes") @pytest.mark.skip(reason="Doesn't work in FactoryBoy at the moment") def test_factory_with_attributes(): """Test that a factory can have a `attributes` field when used as a factory.""" AttributesFactory() @pytest.mark.skip(reason="Doesn't work in FactoryBoy at the moment") def test_factory_fixture_with_attributes(with_attributes): """Test that a factory can have a `attributes` field when used as a fixture.""" pass
from pytest_factoryboy import register from tests.comments import factories as comment_factories from tests.ideas import factories as idea_fatories from tests.ratings import factories as rating_factories register(rating_factories.RatingFactory) register(comment_factories.CommentFactory) register(idea_fatories.IdeaFactory)
from pytest_factoryboy import register from tests.modules import factories as mod_factories from tests.organisations import factories as org_factories from tests.phases import factories as ph_factories from tests.projects import factories register(org_factories.OrganisationFactory) register(factories.ProjectFactory) register(mod_factories.ModuleFactory) register(ph_factories.PhaseFactory)