Best JavaScript code snippet using playwright-internal
test_instances.py
Source:test_instances.py
...6from awx.api.versioning import reverse7from django.utils.timezone import now8@pytest.mark.django_db9def test_default_tower_instance_group(default_instance_group, job_factory):10 assert default_instance_group in job_factory().preferred_instance_groups11@pytest.mark.django_db12class TestPolicyTaskScheduling:13 """Tests make assertions about when the policy task gets scheduled"""14 @pytest.mark.parametrize('field, value, expect', [15 ('name', 'foo-bar-foo-bar', False),16 ('policy_instance_percentage', 35, True),17 ('policy_instance_minimum', 3, True),18 ('policy_instance_list', ['bar?'], True),19 ('modified', now(), False)20 ])21 def test_policy_task_ran_for_ig_when_needed(self, instance_group_factory, field, value, expect):22 # always run on instance group creation23 with mock.patch('awx.main.models.ha.schedule_policy_task') as mock_policy:24 ig = InstanceGroup.objects.create(name='foo')25 mock_policy.assert_called_once()26 # selectively run on instance group modification27 with mock.patch('awx.main.models.ha.schedule_policy_task') as mock_policy:28 setattr(ig, field, value)29 ig.save()30 if expect:31 mock_policy.assert_called_once()32 else:33 mock_policy.assert_not_called()34 @pytest.mark.parametrize('field, value, expect', [35 ('hostname', 'foo-bar-foo-bar', True),36 ('managed_by_policy', False, True),37 ('enabled', False, False),38 ('capacity_adjustment', 0.42, True),39 ('capacity', 42, False)40 ])41 def test_policy_task_ran_for_instance_when_needed(self, instance_group_factory, field, value, expect):42 # always run on instance group creation43 with mock.patch('awx.main.models.ha.schedule_policy_task') as mock_policy:44 inst = Instance.objects.create(hostname='foo')45 mock_policy.assert_called_once()46 # selectively run on instance group modification47 with mock.patch('awx.main.models.ha.schedule_policy_task') as mock_policy:48 setattr(inst, field, value)49 inst.save()50 if expect:51 mock_policy.assert_called_once()52 else:53 mock_policy.assert_not_called()54@pytest.mark.django_db55def test_instance_dup(org_admin, organization, project, instance_factory, instance_group_factory, get, system_auditor):56 i1 = instance_factory("i1")57 i2 = instance_factory("i2")58 i3 = instance_factory("i3")59 ig_all = instance_group_factory("all", instances=[i1, i2, i3])60 ig_dup = instance_group_factory("duplicates", instances=[i1])61 project.organization.instance_groups.add(ig_all, ig_dup)62 actual_num_instances = Instance.objects.active_count()63 list_response = get(reverse('api:instance_list'), user=system_auditor)64 api_num_instances_auditor = list(list_response.data.items())[0][1]65 list_response2 = get(reverse('api:instance_list'), user=org_admin)66 api_num_instances_oa = list(list_response2.data.items())[0][1]67 assert actual_num_instances == api_num_instances_auditor68 # Note: The org_admin will not see the default 'tower' node because it is not in it's group, as expected69 assert api_num_instances_oa == (actual_num_instances - 1)70@pytest.mark.django_db71def test_policy_instance_few_instances(instance_factory, instance_group_factory):72 i1 = instance_factory("i1")73 ig_1 = instance_group_factory("ig1", percentage=25)74 ig_2 = instance_group_factory("ig2", percentage=25)75 ig_3 = instance_group_factory("ig3", percentage=25)76 ig_4 = instance_group_factory("ig4", percentage=25)77 apply_cluster_membership_policies()78 assert len(ig_1.instances.all()) == 179 assert i1 in ig_1.instances.all()80 assert len(ig_2.instances.all()) == 181 assert i1 in ig_2.instances.all()82 assert len(ig_3.instances.all()) == 183 assert i1 in ig_3.instances.all()84 assert len(ig_4.instances.all()) == 185 assert i1 in ig_4.instances.all()86 i2 = instance_factory("i2")87 apply_cluster_membership_policies()88 assert len(ig_1.instances.all()) == 189 assert i1 in ig_1.instances.all()90 assert len(ig_2.instances.all()) == 191 assert i2 in ig_2.instances.all()92 assert len(ig_3.instances.all()) == 193 assert i1 in ig_3.instances.all()94 assert len(ig_4.instances.all()) == 195 assert i2 in ig_4.instances.all()96@pytest.mark.django_db97def test_policy_instance_distribution_round_up(instance_factory, instance_group_factory):98 i1 = instance_factory("i1")99 i2 = instance_factory("i2")100 i3 = instance_factory("i3")101 i4 = instance_factory("i4")102 i5 = instance_factory("i5")103 ig_1 = instance_group_factory("ig1", percentage=79)104 apply_cluster_membership_policies()105 assert len(ig_1.instances.all()) == 4106 assert set([i1, i2, i3, i4]) == set(ig_1.instances.all())107 assert i5 not in ig_1.instances.all()108@pytest.mark.django_db109def test_policy_instance_distribution_uneven(instance_factory, instance_group_factory):110 i1 = instance_factory("i1")111 i2 = instance_factory("i2")112 i3 = instance_factory("i3")113 ig_1 = instance_group_factory("ig1", percentage=25)114 ig_2 = instance_group_factory("ig2", percentage=25)115 ig_3 = instance_group_factory("ig3", percentage=25)116 ig_4 = instance_group_factory("ig4", percentage=25)117 apply_cluster_membership_policies()118 assert len(ig_1.instances.all()) == 1119 assert i1 in ig_1.instances.all()120 assert len(ig_2.instances.all()) == 1121 assert i2 in ig_2.instances.all()122 assert len(ig_3.instances.all()) == 1123 assert i3 in ig_3.instances.all()124 assert len(ig_4.instances.all()) == 1125 assert i1 in ig_4.instances.all()126@pytest.mark.django_db127def test_policy_instance_distribution_even(instance_factory, instance_group_factory):128 i1 = instance_factory("i1")129 i2 = instance_factory("i2")130 i3 = instance_factory("i3")131 i4 = instance_factory("i4")132 ig_1 = instance_group_factory("ig1", percentage=25)133 ig_2 = instance_group_factory("ig2", percentage=25)134 ig_3 = instance_group_factory("ig3", percentage=25)135 ig_4 = instance_group_factory("ig4", percentage=25)136 apply_cluster_membership_policies()137 assert len(ig_1.instances.all()) == 1138 assert i1 in ig_1.instances.all()139 assert len(ig_2.instances.all()) == 1140 assert i2 in ig_2.instances.all()141 assert len(ig_3.instances.all()) == 1142 assert i3 in ig_3.instances.all()143 assert len(ig_4.instances.all()) == 1144 assert i4 in ig_4.instances.all()145 ig_1.policy_instance_minimum = 2146 ig_1.save()147 apply_cluster_membership_policies()148 assert len(ig_1.instances.all()) == 2149 assert i1 in ig_1.instances.all()150 assert i2 in ig_1.instances.all()151 assert len(ig_2.instances.all()) == 1152 assert i3 in ig_2.instances.all()153 assert len(ig_3.instances.all()) == 1154 assert i4 in ig_3.instances.all()155 assert len(ig_4.instances.all()) == 1156 assert i1 in ig_4.instances.all()157@pytest.mark.django_db158def test_policy_instance_distribution_simultaneous(instance_factory, instance_group_factory):159 i1 = instance_factory("i1")160 i2 = instance_factory("i2")161 i3 = instance_factory("i3")162 i4 = instance_factory("i4")163 ig_1 = instance_group_factory("ig1", percentage=25, minimum=2)164 ig_2 = instance_group_factory("ig2", percentage=25)165 ig_3 = instance_group_factory("ig3", percentage=25)166 ig_4 = instance_group_factory("ig4", percentage=25)167 apply_cluster_membership_policies()168 assert len(ig_1.instances.all()) == 2169 assert i1 in ig_1.instances.all()170 assert i2 in ig_1.instances.all()171 assert len(ig_2.instances.all()) == 1172 assert i3 in ig_2.instances.all()173 assert len(ig_3.instances.all()) == 1174 assert i4 in ig_3.instances.all()175 assert len(ig_4.instances.all()) == 1176 assert i1 in ig_4.instances.all()177@pytest.mark.django_db178def test_policy_instance_list_manually_assigned(instance_factory, instance_group_factory):179 i1 = instance_factory("i1")180 i2 = instance_factory("i2")181 ig_1 = instance_group_factory("ig1", percentage=100, minimum=2)182 ig_2 = instance_group_factory("ig2")183 ig_2.policy_instance_list = [i2.hostname]184 ig_2.save()185 apply_cluster_membership_policies()186 assert len(ig_1.instances.all()) == 2187 assert i1 in ig_1.instances.all()188 assert i2 in ig_1.instances.all()189 assert len(ig_2.instances.all()) == 1190 assert i2 in ig_2.instances.all()191@pytest.mark.django_db192def test_policy_instance_list_explicitly_pinned(instance_factory, instance_group_factory):193 i1 = instance_factory("i1")194 i2 = instance_factory("i2")195 ig_1 = instance_group_factory("ig1", percentage=100, minimum=2)196 ig_2 = instance_group_factory("ig2")197 ig_2.policy_instance_list = [i2.hostname]198 ig_2.save()199 # without being marked as manual, i2 will be picked up by ig_1200 apply_cluster_membership_policies()201 assert set(ig_1.instances.all()) == set([i1, i2])202 assert set(ig_2.instances.all()) == set([i2])203 i2.managed_by_policy = False204 i2.save()205 # after marking as manual, i2 no longer available for ig_1206 apply_cluster_membership_policies()207 assert set(ig_1.instances.all()) == set([i1])208 assert set(ig_2.instances.all()) == set([i2])209@pytest.mark.django_db210def test_basic_instance_group_membership(instance_group_factory, default_instance_group, job_factory):211 j = job_factory()212 ig = instance_group_factory("basicA", [default_instance_group.instances.first()])213 j.job_template.instance_groups.add(ig)214 assert ig in j.preferred_instance_groups215 assert default_instance_group not in j.preferred_instance_groups216@pytest.mark.django_db217def test_inherited_instance_group_membership(instance_group_factory, default_instance_group, job_factory, project, inventory):218 j = job_factory()219 j.project = project220 j.inventory = inventory221 ig_org = instance_group_factory("basicA", [default_instance_group.instances.first()])222 ig_inv = instance_group_factory("basicB", [default_instance_group.instances.first()])223 j.project.organization.instance_groups.add(ig_org)224 j.inventory.instance_groups.add(ig_inv)225 assert ig_org in j.preferred_instance_groups226 assert ig_inv in j.preferred_instance_groups227 assert default_instance_group not in j.preferred_instance_groups228@pytest.mark.django_db229def test_mixed_group_membership(instance_factory, instance_group_factory):230 for i in range(5):231 instance_factory("i{}".format(i))232 ig_1 = instance_group_factory("ig1", percentage=60)233 ig_2 = instance_group_factory("ig2", minimum=3)234 ig_3 = instance_group_factory("ig3", minimum=1, percentage=60)235 apply_cluster_membership_policies()236 for group in (ig_1, ig_2, ig_3):237 assert len(group.instances.all()) == 3238@pytest.mark.django_db239def test_instance_group_capacity(instance_factory, instance_group_factory):240 i1 = instance_factory("i1")241 i2 = instance_factory("i2")242 i3 = instance_factory("i3")243 ig_all = instance_group_factory("all", instances=[i1, i2, i3])244 assert ig_all.capacity == 300245 ig_single = instance_group_factory("single", instances=[i1])246 assert ig_single.capacity == 100247@pytest.mark.django_db248class TestInstanceGroupOrdering:249 def test_ad_hoc_instance_groups(self, instance_group_factory, inventory, default_instance_group):250 ad_hoc = AdHocCommand.objects.create(inventory=inventory)251 assert ad_hoc.preferred_instance_groups == [default_instance_group]252 ig_org = instance_group_factory("OrgIstGrp", [default_instance_group.instances.first()])253 ig_inv = instance_group_factory("InvIstGrp", [default_instance_group.instances.first()])254 inventory.organization.instance_groups.add(ig_org)255 assert ad_hoc.preferred_instance_groups == [ig_org]256 inventory.instance_groups.add(ig_inv)257 assert ad_hoc.preferred_instance_groups == [ig_inv, ig_org]258 def test_inventory_update_instance_groups(self, instance_group_factory, inventory_source, default_instance_group):259 iu = InventoryUpdate.objects.create(inventory_source=inventory_source)260 assert iu.preferred_instance_groups == [default_instance_group]261 ig_org = instance_group_factory("OrgIstGrp", [default_instance_group.instances.first()])262 ig_inv = instance_group_factory("InvIstGrp", [default_instance_group.instances.first()])263 ig_tmp = instance_group_factory("TmpIstGrp", [default_instance_group.instances.first()])264 inventory_source.inventory.organization.instance_groups.add(ig_org)265 inventory_source.inventory.instance_groups.add(ig_inv)266 assert iu.preferred_instance_groups == [ig_inv, ig_org]267 inventory_source.instance_groups.add(ig_tmp)268 # API does not allow setting IGs on inventory source, so ignore those269 assert iu.preferred_instance_groups == [ig_inv, ig_org]270 def test_project_update_instance_groups(self, instance_group_factory, project, default_instance_group):271 pu = ProjectUpdate.objects.create(project=project)272 assert pu.preferred_instance_groups == [default_instance_group]273 ig_org = instance_group_factory("OrgIstGrp", [default_instance_group.instances.first()])274 ig_tmp = instance_group_factory("TmpIstGrp", [default_instance_group.instances.first()])275 project.organization.instance_groups.add(ig_org)276 assert pu.preferred_instance_groups == [ig_org]277 project.instance_groups.add(ig_tmp)278 assert pu.preferred_instance_groups == [ig_tmp, ig_org]279 def test_job_instance_groups(self, instance_group_factory, inventory, project, default_instance_group):280 jt = JobTemplate.objects.create(inventory=inventory, project=project)281 job = Job.objects.create(inventory=inventory, job_template=jt, project=project)282 assert job.preferred_instance_groups == [default_instance_group]283 ig_org = instance_group_factory("OrgIstGrp", [default_instance_group.instances.first()])284 ig_inv = instance_group_factory("InvIstGrp", [default_instance_group.instances.first()])285 ig_tmp = instance_group_factory("TmpIstGrp", [default_instance_group.instances.first()])286 project.organization.instance_groups.add(ig_org)287 inventory.instance_groups.add(ig_inv)288 assert job.preferred_instance_groups == [ig_inv, ig_org]289 job.job_template.instance_groups.add(ig_tmp)...
test_migrate.py
Source:test_migrate.py
1#!/usr/bin/env python32# Copyright 2018 Google LLC3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# https://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15import os16import sys17import unittest18sys.path.append(19 os.path.abspath(20 os.path.join(21 os.path.dirname(__file__),22 '../../helpers/')))23import migrate # noqa: E40224TERRAFORM_STATE_LIST = [25 "google_compute_instance.test",26 "google_project_iam_member.user-editor",27 "module.project-factory.google_compute_default_service_account.default",28 "module.project-factory.google_compute_shared_vpc_service_project.shared_vpc_attachment", # noqa: E50129 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[0]", # noqa: E50130 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[1]", # noqa: E50131 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[2]", # noqa: E50132 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[0]", # noqa: E50133 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[1]", # noqa: E50134 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[2]", # noqa: E50135 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[0]", # noqa: E50136 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[1]", # noqa: E50137 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[2]", # noqa: E50138 "module.project-factory.google_organization.org",39 "module.project-factory.google_project.project",40 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[0]", # noqa: E50141 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[1]", # noqa: E50142 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[2]", # noqa: E50143 "module.project-factory.google_project_iam_member.gsuite_group_role",44 "module.project-factory.google_project_service.project_services",45 "module.project-factory.google_service_account.default_service_account",46 "module.project-factory.google_service_account_iam_member.service_account_grant_to_group", # noqa: E50147 "module.project-factory.gsuite_group.group",48 "module.project-factory.gsuite_group_member.api_s_account_api_sa_group_member", # noqa: E50149 "module.project-factory.null_data_source.data_final_group_email",50 "module.project-factory.null_data_source.data_given_group_email",51 "module.project-factory.null_data_source.data_group_email_format",52 "module.project-factory.null_resource.delete_default_compute_service_account", # noqa: E50153 "module.project-factory.random_id.random_project_id_suffix",54]55TERRAFORM_MOVES = [56 (57 "module.project-factory.google_compute_shared_vpc_service_project.shared_vpc_attachment", # noqa: E50158 "module.project-factory.module.project-factory.google_compute_shared_vpc_service_project.shared_vpc_attachment", # noqa: E50159 ),60 (61 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[0]", # noqa: E50162 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[0]", # noqa: E50163 ),64 (65 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[1]", # noqa: E50166 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[1]", # noqa: E50167 ),68 (69 "module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[2]", # noqa: E50170 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.apis_service_account_role_to_vpc_subnets[2]", # noqa: E50171 ),72 (73 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[0]", # noqa: E50174 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[0]", # noqa: E50175 ),76 (77 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[1]", # noqa: E50178 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[1]", # noqa: E50179 ),80 (81 "module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[2]", # noqa: E50182 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.group_role_to_vpc_subnets[2]", # noqa: E50183 ),84 (85 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[0]", # noqa: E50186 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[0]", # noqa: E50187 ),88 (89 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[1]", # noqa: E50190 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[1]", # noqa: E50191 ),92 (93 "module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[2]", # noqa: E50194 "module.project-factory.module.project-factory.google_compute_subnetwork_iam_member.service_account_role_to_vpc_subnets[2]", # noqa: E50195 ),96 (97 "module.project-factory.google_project.project",98 "module.project-factory.module.project-factory.google_project.main",99 ),100 (101 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[0]", # noqa: E501102 "module.project-factory.module.project-factory.google_project_iam_member.controlling_group_vpc_membership[0]", # noqa: E501103 ),104 (105 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[1]", # noqa: E501106 "module.project-factory.module.project-factory.google_project_iam_member.controlling_group_vpc_membership[1]", # noqa: E501107 ),108 (109 "module.project-factory.google_project_iam_member.controlling_group_vpc_membership[2]", # noqa: E501110 "module.project-factory.module.project-factory.google_project_iam_member.controlling_group_vpc_membership[2]", # noqa: E501111 ),112 (113 "module.project-factory.google_project_iam_member.gsuite_group_role",114 "module.project-factory.module.project-factory.google_project_iam_member.gsuite_group_role", # noqa: E501115 ),116 (117 "module.project-factory.google_project_service.project_services",118 "module.project-factory.module.project-factory.google_project_service.project_services", # noqa: E501119 ),120 (121 "module.project-factory.google_service_account.default_service_account", # noqa: E501122 "module.project-factory.module.project-factory.google_service_account.default_service_account", # noqa: E501123 ),124 (125 "module.project-factory.google_service_account_iam_member.service_account_grant_to_group", # noqa: E501126 "module.project-factory.module.project-factory.google_service_account_iam_member.service_account_grant_to_group", # noqa: E501127 ),128 (129 "module.project-factory.null_resource.delete_default_compute_service_account", # noqa: E501130 "module.project-factory.module.project-factory.null_resource.delete_default_compute_service_account", # noqa: E501131 ),132 (133 "module.project-factory.random_id.random_project_id_suffix",134 "module.project-factory.module.project-factory.random_id.random_project_id_suffix", # noqa: E501135 ),136]137# The following entities are data sources that are not part of the 1.0138# migration process and should not be present in the list of resource139# moves.140TERRAFORM_DROPPED_DATA_SOURCES = [141 (142 "module.project-factory.google_organization.org",143 "module.project-factory.module.project-factory.google_organization.org", # noqa: E501144 ),145 (146 "module.project-factory.null_data_source.data_final_group_email",147 "module.project-factory.module.project-factory.null_data_source.data_final_group_email", # noqa: E501148 ),149 (150 "module.project-factory.null_data_source.data_given_group_email",151 "module.project-factory.module.project-factory.null_data_source.data_given_group_email", # noqa: E501152 ),153 (154 "module.project-factory.null_data_source.data_group_email_format",155 "module.project-factory.module.project-factory.null_data_source.data_group_email_format", # noqa: E501156 ),157]158# The following entities are resources that were not part of the migration159# and should not be present in the list of resource moves.160TERRAFORM_UNMIGRATED_MOVES = [161 (162 "module.project-factory.gsuite_group.group",163 "module.project-factory.module.project-factory.gsuite_group.group",164 ),165 (166 "module.project-factory.gsuite_group_member.api_s_account_api_sa_group_member", # noqa: E501167 "module.project-factory.module.project-factory.gsuite_group_member.api_s_account_api_sa_group_member", # noqa: E501168 ),169]170class TestGSuiteMigration(unittest.TestCase):171 def setUp(self):172 self.resources = [173 migrate.TerraformResource.from_path(path)174 for path in TERRAFORM_STATE_LIST175 ]176 self.module = migrate.TerraformModule(177 'module.project-factory',178 self.resources)179 self.migration = migrate.GSuiteMigration(self.module)180 def test_moves(self):181 computed_moves = self.migration.moves()182 self.assertEqual(set(computed_moves), set(TERRAFORM_MOVES))183 def test_no_moves_of_data_sources(self):184 computed_moves = self.migration.moves()185 self.assertTrue(186 set(TERRAFORM_DROPPED_DATA_SOURCES).isdisjoint(computed_moves))187 def test_no_moves_of_unmigrated_resources(self):188 computed_moves = self.migration.moves()189 self.assertTrue(190 set(TERRAFORM_UNMIGRATED_MOVES).isdisjoint(computed_moves))191 def test_no_moves_outside_of_module(self):192 computed_moves = self.migration.moves()193 old_resources = [move[0] for move in computed_moves]194 self.assertFalse("google_compute_instance.test" in old_resources)195 self.assertFalse(196 "google_project_iam_member.user-editor" in old_resources)197class TestTerraformModule(unittest.TestCase):198 def setUp(self):199 self.resources = [200 migrate.TerraformResource.from_path(path)201 for path in TERRAFORM_STATE_LIST202 ]203 self.module = migrate.TerraformModule(204 'module.project-factory',205 self.resources)206 def test_has_resource(self):207 self.assertTrue(self.module.has_resource('google_project', 'project'))208 self.assertTrue(self.module.has_resource(None, 'project'))209 self.assertTrue(self.module.has_resource('google_project', None))210 self.assertTrue(self.module.has_resource(None, None))211 def test_has_resource_empty(self):212 self.assertFalse(213 self.module.has_resource('google_cloudiot_registry', None))214 def test_get_resources(self):215 expected = [resource for resource in self.resources216 if resource.resource_type == 'google_project_iam_member']217 actual = self.module.get_resources('google_project_iam_member', None)218 self.assertEqual(actual, expected)219 def test_get_resources_empty(self):220 actual = self.module.get_resources('google_cloudiot_registry', None)221 self.assertTrue(len(actual) == 0)222class TestTerraformResource(unittest.TestCase):223 def test_root_resource_from_path(self):224 resource = migrate.TerraformResource.from_path(225 "google_project.project")226 self.assertEqual(resource.module, '')227 self.assertEqual(resource.resource_type, 'google_project')228 self.assertEqual(resource.name, 'project')229 def test_module_resource_from_path(self):230 resource = migrate.TerraformResource.from_path(231 "module.project-factory.google_project.project")232 self.assertEqual(resource.module, 'module.project-factory')233 self.assertEqual(resource.resource_type, 'google_project')234 self.assertEqual(resource.name, 'project')235 def test_invalid_resource_from_path(self):236 self.assertRaises(237 Exception,238 lambda: migrate.TerraformResource.from_path("not a resource path!")239 )240 def test_resource_init(self):241 resource = migrate.TerraformResource('', 'google_project', 'project')242 self.assertEqual(resource.module, '')243 self.assertEqual(resource.resource_type, 'google_project')244 self.assertEqual(resource.name, 'project')245 def test_resource_path_no_module(self):246 resource = migrate.TerraformResource('', 'google_project', 'project')247 self.assertEqual(resource.path(), 'google_project.project')248 def test_resource_path_with_module(self):249 resource = migrate.TerraformResource('module.project-factory',250 'google_project', 'project')251 expected = 'module.project-factory.google_project.project'252 actual = resource.path()253 self.assertEqual(expected, actual)254if __name__ == "__main__":...
test_triples_factory.py
Source:test_triples_factory.py
1# -*- coding: utf-8 -*-2"""Unit tests for triples factories."""3import unittest4import numpy as np5from pykeen.datasets import Nations6from pykeen.triples import TriplesFactory, TriplesNumericLiteralsFactory7from pykeen.triples.triples_factory import INVERSE_SUFFIX8triples = np.array(9 [10 ['peter', 'likes', 'chocolate_cake'],11 ['chocolate_cake', 'isA', 'dish'],12 ['susan', 'likes', 'pizza'],13 ['peter', 'likes', 'susan'],14 ],15 dtype=np.str,16)17instance_mapped_triples = np.array(18 [19 [0, 0],20 [2, 1],21 [4, 1],22 ],23)24instance_labels = np.array(25 [26 np.array([1]),27 np.array([0, 4]),28 np.array([3]),29 ],30)31numeric_triples = np.array(32 [33 ['peter', '/lit/hasAge', '30'],34 ['peter', '/lit/hasHeight', '185'],35 ['peter', '/lit/hasChildren', '2'],36 ['susan', '/lit/hasAge', '28'],37 ['susan', '/lit/hasHeight', '170'],38 ],39 dtype=np.str,40)41class TestTriplesFactory(unittest.TestCase):42 """Class for testing triples factories."""43 def test_correct_inverse_creation(self):44 """Test if the triples and the corresponding inverses are created and sorted correctly."""45 t = [46 ['e1', 'a.', 'e5'],47 ['e1', 'a', 'e2'],48 ]49 t = np.array(t, dtype=np.str)50 factory = TriplesFactory(triples=t, create_inverse_triples=True)51 reference_relation_to_id = {'a': 0, f'a{INVERSE_SUFFIX}': 1, 'a.': 2, f'a.{INVERSE_SUFFIX}': 3}52 self.assertEqual(reference_relation_to_id, factory.relation_to_id)53 def test_automatic_inverse_detection(self):54 """Test if the TriplesFactory detects that the triples contain inverses and creates correct ids."""55 t = [56 ['e3', f'a.{INVERSE_SUFFIX}', 'e10'],57 ['e1', 'a', 'e2'],58 ['e1', 'a.', 'e5'],59 ['e4', f'a{INVERSE_SUFFIX}', 'e5'],60 ]61 t = np.array(t, dtype=np.str)62 factory = TriplesFactory(triples=t, create_inverse_triples=False)63 reference_relation_to_id = {'a': 0, f'a{INVERSE_SUFFIX}': 1, 'a.': 2, f'a.{INVERSE_SUFFIX}': 3}64 self.assertEqual(reference_relation_to_id, factory.relation_to_id)65 self.assertTrue(factory.create_inverse_triples)66 def test_automatic_incomplete_inverse_detection(self):67 """Test if the TriplesFactory detects that the triples contain incomplete inverses and creates correct ids."""68 t = [69 ['e3', f'a.{INVERSE_SUFFIX}', 'e10'],70 ['e1', 'a', 'e2'],71 ['e1', 'a.', 'e5'],72 ]73 t = np.array(t, dtype=np.str)74 factory = TriplesFactory(triples=t, create_inverse_triples=False)75 reference_relation_to_id = {'a': 0, f'a{INVERSE_SUFFIX}': 1, 'a.': 2, f'a.{INVERSE_SUFFIX}': 3}76 self.assertEqual(reference_relation_to_id, factory.relation_to_id)77 self.assertTrue(factory.create_inverse_triples)78 def test_right_sorting(self):79 """Test if the triples and the corresponding inverses are sorted correctly."""80 t = [81 ['e1', 'a', 'e1'],82 ['e1', 'a.', 'e1'],83 ['e1', f'a.{INVERSE_SUFFIX}', 'e1'],84 ['e1', 'a.bc', 'e1'],85 ['e1', f'a.bc{INVERSE_SUFFIX}', 'e1'],86 ['e1', f'a{INVERSE_SUFFIX}', 'e1'],87 ['e1', 'abc', 'e1'],88 ['e1', f'abc{INVERSE_SUFFIX}', 'e1'],89 ]90 t = np.array(t, dtype=np.str)91 factory = TriplesFactory(triples=t, create_inverse_triples=False)92 reference_relation_to_id = {93 'a': 0,94 f'a{INVERSE_SUFFIX}': 1,95 'a.': 2,96 f'a.{INVERSE_SUFFIX}': 3,97 'a.bc': 4,98 f'a.bc{INVERSE_SUFFIX}': 5,99 'abc': 6,100 f'abc{INVERSE_SUFFIX}': 7,101 }102 self.assertEqual(reference_relation_to_id, factory.relation_to_id)103class TestSplit(unittest.TestCase):104 """Test splitting."""105 triples_factory: TriplesFactory106 def setUp(self) -> None:107 """Set up the tests."""108 self.triples_factory = Nations().training109 self.assertEqual(1592, self.triples_factory.num_triples)110 def test_split_naive(self):111 """Test splitting a factory in two with a given ratio."""112 ratio = 0.8113 train_triples_factory, test_triples_factory = self.triples_factory.split(ratio)114 expected_train_triples = int(self.triples_factory.num_triples * ratio)115 self.assertEqual(expected_train_triples, train_triples_factory.num_triples)116 self.assertEqual(self.triples_factory.num_triples - expected_train_triples, test_triples_factory.num_triples)117 def test_split_multi(self):118 """Test splitting a factory in three."""119 ratios = r0, r1 = 0.80, 0.10120 t0, t1, t2 = self.triples_factory.split(ratios)121 expected_0_triples = int(self.triples_factory.num_triples * r0)122 expected_1_triples = int(self.triples_factory.num_triples * r1)123 expected_2_triples = self.triples_factory.num_triples - expected_0_triples - expected_1_triples124 self.assertEqual(expected_0_triples, t0.num_triples)125 self.assertEqual(expected_1_triples, t1.num_triples)126 self.assertEqual(expected_2_triples, t2.num_triples)127class TestLiterals(unittest.TestCase):128 """Class for testing utils for processing numeric literals.tsv."""129 def test_create_lcwa_instances(self):130 """Test creating LCWA instances."""131 factory = TriplesNumericLiteralsFactory(triples=triples, numeric_triples=numeric_triples)132 instances = factory.create_lcwa_instances()133 id_peter = factory.entity_to_id['peter']134 id_age = instances.literals_to_id['/lit/hasAge']135 id_height = instances.literals_to_id['/lit/hasHeight']136 id_num_children = instances.literals_to_id['/lit/hasChildren']137 self.assertEqual(instances.numeric_literals[id_peter, id_age], 30)138 self.assertEqual(instances.numeric_literals[id_peter, id_height], 185)139 self.assertEqual(instances.numeric_literals[id_peter, id_num_children], 2)140 id_susan = factory.entity_to_id['susan']141 id_age = instances.literals_to_id['/lit/hasAge']142 id_height = instances.literals_to_id['/lit/hasHeight']143 id_num_children = instances.literals_to_id['/lit/hasChildren']144 self.assertEqual(instances.numeric_literals[id_susan, id_age], 28)145 self.assertEqual(instances.numeric_literals[id_susan, id_height], 170)146 self.assertEqual(instances.numeric_literals[id_susan, id_num_children], 0)147 id_chocolate_cake = factory.entity_to_id['chocolate_cake']148 id_age = instances.literals_to_id['/lit/hasAge']149 id_height = instances.literals_to_id['/lit/hasHeight']150 id_num_children = instances.literals_to_id['/lit/hasChildren']151 self.assertEqual(instances.numeric_literals[id_chocolate_cake, id_age], 0)152 self.assertEqual(instances.numeric_literals[id_chocolate_cake, id_height], 0)153 self.assertEqual(instances.numeric_literals[id_chocolate_cake, id_num_children], 0)154 # Check if multilabels are working correctly155 self.assertTrue((instance_mapped_triples == instances.mapped_triples.cpu().detach().numpy()).all())156 self.assertTrue(all(all(instance_labels[i] == instances.labels[i]) for i in range(len(instance_labels))))157 def test_triples(self):158 """Test properties of the triples factory."""159 triples_factory = TriplesFactory(triples=triples)160 self.assertEqual(set(range(triples_factory.num_entities)), set(triples_factory.entity_to_id.values()))161 self.assertEqual(set(range(triples_factory.num_relations)), set(triples_factory.relation_to_id.values()))162 self.assertTrue((triples_factory.mapped_triples == triples_factory.map_triples_to_id(triples)).all())163 def test_inverse_triples(self):164 """Test that the right number of entities and triples exist after inverting them."""165 triples_factory = TriplesFactory(triples=triples, create_inverse_triples=True)166 self.assertEqual(0, triples_factory.num_relations % 2)167 self.assertEqual(168 set(range(triples_factory.num_entities)),169 set(triples_factory.entity_to_id.values()),170 msg='wrong number entities',171 )172 self.assertEqual(173 set(range(triples_factory.num_relations)),174 set(triples_factory.relation_to_id.values()),175 msg='wrong number relations',176 )177 relations = set(triples[:, 1])178 entities = set(triples[:, 0]).union(triples[:, 2])179 self.assertEqual(len(entities), triples_factory.num_entities, msg='wrong number entities')180 self.assertEqual(2, len(relations), msg='Wrong number of relations in set')181 self.assertEqual(182 2 * len(relations),183 triples_factory.num_relations,184 msg='Wrong number of relations in factory',185 )...
test_paint_factory.py
Source:test_paint_factory.py
1from exam_preparation.exam_19_12_2020.tests.project.factory.paint_factory import PaintFactory2from unittest import TestCase, main3# class TestPaintFactory(TestCase):4#5# def setUp(self):6# self.paint_factory = PaintFactory('Slatina', 50)7#8# def test_initial_atributtes(self):9# self.assertEqual('Slatina', self.paint_factory.name)10# self.assertEqual(50, self.paint_factory.capacity)11# self.assertListEqual(["white", "yellow", "blue", "green", "red"], self.paint_factory.valid_ingredients)12# self.assertDictEqual({}, self.paint_factory.ingredients)13# self.assertDictEqual({}, self.paint_factory.products)14#15# def test_add_method_invalid_ingredient(self):16# with self.assertRaises(TypeError) as context:17# self.paint_factory.add_ingredient('orange', 20)18# self.assertEqual("Ingredient of type orange not allowed in PaintFactory", str(context.exception))19#20# def test_add_method_invalid_quantity(self):21# with self.assertRaises(ValueError) as context:22# self.paint_factory.add_ingredient('green', 55)23# self.assertEqual("Not enough space in factory", str(context.exception))24#25# def test_add_method_valid_ingredient_and_quantity(self):26# self.paint_factory.add_ingredient('green', 25)27# self.paint_factory.add_ingredient('white', 25)28# self.assertEqual({'green': 25, 'white': 25}, self.paint_factory.ingredients)29#30# def test_remove_method_invalid_ingredient(self):31# with self.assertRaises(KeyError) as context:32# self.paint_factory.remove_ingredient('orange', 20)33# self.assertEqual("No such product in the factory", context.exception.args[0])34#35# def test_remove_method_invalid_quantity(self):36# self.paint_factory.add_ingredient('green', 25)37# with self.assertRaises(ValueError) as context:38# self.paint_factory.remove_ingredient('green', 30)39# self.assertEqual("Ingredient quantity cannot be less than zero", str(context.exception))40#41# def test_remove_method_valid_ingredient_and_quantity(self):42# self.paint_factory.add_ingredient('green', 25)43# self.paint_factory.remove_ingredient('green', 25)44# self.assertEqual({'green': 0}, self.paint_factory.ingredients)45#46# def test_products_property(self):47# self.paint_factory.add_ingredient('green', 25)48# self.paint_factory.add_ingredient('white', 25)49# self.assertEqual({'green': 25, 'white': 25}, self.paint_factory.ingredients)50#51# def test_can_add_method_false_from_base_class(self):52# self.paint_factory.add_ingredient('green', 20)53# self.paint_factory.add_ingredient('white', 20)54# self.assertTrue(self.paint_factory.can_add(10))55#56# def test_can_add_method_true_from_base_class(self):57# self.paint_factory.add_ingredient('green', 25)58# self.paint_factory.add_ingredient('white', 25)59# self.assertFalse(self.paint_factory.can_add(10))60#61# def test__repr__method(self):62# self.paint_factory.add_ingredient('green', 20)63# result = self.paint_factory.__repr__()64# expected = "Factory name: Slatina with capacity 50.\ngreen: 20\n"65# self.assertEqual(expected, result)66class TestPaintFactory(TestCase):67 def setUp(self):68 self.paint_factory = PaintFactory('Slatina', 50)69 def test_initial_atributtes(self):70 self.assertEqual('Slatina', self.paint_factory.name)71 self.assertEqual(50, self.paint_factory.capacity)72 # self.assertListEqual(["white", "yellow", "blue", "green", "red"], self.paint_factory.valid_ingredients)73 self.assertDictEqual({}, self.paint_factory.ingredients)74 self.assertDictEqual({}, self.paint_factory.products)75 def test_add_method_invalid_ingredient(self):76 with self.assertRaises(TypeError) as context:77 self.paint_factory.add_ingredient('orange', 20)78 self.assertEqual("Ingredient of type orange not allowed in PaintFactory", str(context.exception))79 def test_add_method_invalid_quantity(self):80 with self.assertRaises(ValueError) as context:81 self.paint_factory.add_ingredient('green', 55)82 self.assertEqual("Not enough space in factory", str(context.exception))83 def test_add_method_valid_ingredient_and_quantity(self):84 self.paint_factory.add_ingredient('green', 25)85 self.paint_factory.add_ingredient('white', 25)86 self.assertEqual({'green': 25, 'white': 25}, self.paint_factory.ingredients)87 def test_remove_method_invalid_ingredient(self):88 with self.assertRaises(KeyError) as context:89 self.paint_factory.remove_ingredient('orange', 20)90 self.assertEqual("No such ingredient in the factory", context.exception.args[0])91 def test_remove_method_invalid_quantity(self):92 self.paint_factory.add_ingredient('green', 25)93 with self.assertRaises(ValueError) as context:94 self.paint_factory.remove_ingredient('green', 30)95 self.assertEqual("Ingredients quantity cannot be less than zero", str(context.exception))96 def test_remove_method_valid_ingredient_and_quantity(self):97 self.paint_factory.add_ingredient('green', 25)98 self.paint_factory.remove_ingredient('green', 25)99 self.assertEqual({'green': 0}, self.paint_factory.ingredients)100 def test_products_property(self):101 self.paint_factory.add_ingredient('green', 25)102 self.paint_factory.add_ingredient('white', 25)103 self.assertEqual({'green': 25, 'white': 25}, self.paint_factory.ingredients)104 def test_can_add_method_false_from_base_class(self):105 self.paint_factory.add_ingredient('green', 20)106 self.paint_factory.add_ingredient('white', 20)107 self.assertTrue(self.paint_factory.can_add(10))108 def test_can_add_method_true_from_base_class(self):109 self.paint_factory.add_ingredient('green', 25)110 self.paint_factory.add_ingredient('white', 25)111 self.assertFalse(self.paint_factory.can_add(10))112 def test__repr__method(self):113 self.paint_factory.add_ingredient('green', 20)114 result = self.paint_factory.__repr__()115 expected = "Factory name: Slatina with capacity 50.\ngreen: 20\n"116 self.assertEqual(expected, result)117if __name__ == '__main__':...
collection.py
Source:collection.py
1"""2extMediaCollection factory to execute tests3"""4import factory5from ...models.collection import Collection6from .location_gis import LocationGisFactory7from .mediatype import MediaTypeFactory8from .legalrights import LegalRightsFactory9from .publisher import PublisherFactory10from .acquisition_mode import AcquisitionModeFactory11from .recording_context import RecordingContextFactory12from .collectioncollectors import CollectionCollectorsFactory13from .collection_informer import CollectionInformerFactory14from .collection_location import CollectionLocationFactory15from .collection_language import CollectionLanguageFactory16from .collection_publisher import CollectionPublisherFactory17from .performancecollectionmusician import PerformanceCollectionMusicianFactory18from .performancecollection import PerformanceCollectionFactory19from .item import ItemCollectionFactory20class CollectionFactory(factory.django.DjangoModelFactory):21 """22 Collection factory23 """24 code = factory.Sequence(lambda n: 'code{0}'.format(n))25 class Meta:26 model = Collection27 mission = factory.SubFactory("francoralite.apps.francoralite_api.tests.factories.fond.MissionFactory")28 title = factory.Faker('word')29 alt_title = factory.Faker('word')30 description = factory.Faker('paragraph', nb_sentences=5)31 # descriptions = factory.Faker('paragraph', nb_sentences=5)32 recording_context = factory.Faker('word')33 recorded_from_year = factory.Faker('date')34 recorded_to_year = factory.Faker('date')35 year_published = factory.Faker('year')36 # location = factory.SubFactory(LocationGisFactory)37 location_details = factory.Faker('paragraph', nb_sentences=3)38 cultural_area = factory.Faker('paragraph', nb_sentences=1)39 language = factory.Faker('word')40 # publisher = factory.SubFactory(PublisherFactory)41 # publisher = factory.Faker('word')42 # publisher_collection = factory.SubFactory(CollectionPublisherFactory)43 publisher_collection = factory.Faker('word')44 booklet_author = factory.Faker('word')45 metadata_author = factory.Faker('word')46 code_partner = factory.Faker('word')47 booklet_description = factory.Faker('paragraph', nb_sentences=3)48 comment = factory.Faker('paragraph', nb_sentences=5)49 media_type = factory.SubFactory(MediaTypeFactory)50 physical_items_num = factory.Faker('pyint')51 auto_period_access = factory.Faker('boolean')52 legal_rights = factory.SubFactory(LegalRightsFactory)53 # public_access = factory.Faker('word')54class CollectionCompleteFactory(CollectionFactory):55 """56 Collection with all related entities57 """58 @factory.post_generation59 def complete( self, create, extracted, **kwargs):60 if not create: return61 CollectionCollectorsFactory.create_batch(2, collection = self)62 CollectionInformerFactory.create_batch(2, collection = self)63 CollectionLocationFactory.create_batch(2, collection = self)64 CollectionLanguageFactory.create_batch(2, collection = self)65 CollectionPublisherFactory.create_batch(2, collection = self)66 perfs = PerformanceCollectionFactory.create_batch(2, collection = self)67 for perf in perfs:68 PerformanceCollectionMusicianFactory.create_batch(69 2, performance_collection = perf)70 ItemCollectionFactory.create_batch(3, collection = self)71 72class CollectionItemsFactory(CollectionFactory):73 """74 Collection with items related75 """76 @factory.post_generation77 def items( self, create, extracted, **kwargs):78 if not create: return...
factories.py
Source:factories.py
1# coding: utf-82import string3from datetime import datetime4import factory5from django.contrib.auth.models import User6from factory.fuzzy import FuzzyText7from accounts import models as account_models8from scheduler import models as scheduler_models9from places import models as places_models10from organizations import models as organization_models11class CountryFactory(factory.DjangoModelFactory):12 class Meta:13 model = places_models.Country14 name = factory.Sequence(lambda n: 'Country ' + str(n))15 slug = factory.Sequence(lambda n: 'country_' + str(n))16class RegionFactory(factory.DjangoModelFactory):17 class Meta:18 model = places_models.Region19 name = factory.Sequence(lambda n: 'Region ' + str(n))20 slug = factory.Sequence(lambda n: 'region_' + str(n))21 country = factory.SubFactory(CountryFactory)22class AreaFactory(factory.DjangoModelFactory):23 class Meta:24 model = places_models.Area25 name = factory.Sequence(lambda n: 'Area ' + str(n))26 slug = factory.Sequence(lambda n: 'area_' + str(n))27 region = factory.SubFactory(RegionFactory)28class PlaceFactory(factory.DjangoModelFactory):29 class Meta:30 model = places_models.Place31 name = factory.Sequence(lambda n: 'Place ' + str(n))32 slug = factory.Sequence(lambda n: 'place_' + str(n))33 area = factory.SubFactory(AreaFactory)34class OrganizationFactory(factory.DjangoModelFactory):35 name = factory.Sequence(lambda n: 'Organization ' + str(n))36 slug = factory.Sequence(lambda n: 'org_' + str(n))37 class Meta:38 model = organization_models.Organization39 django_get_or_create = ['name']40class FacilityFactory(factory.DjangoModelFactory):41 name = factory.Sequence(lambda n: 'Facility ' + str(n))42 slug = factory.Sequence(lambda n: 'facility_' + str(n))43 place = factory.SubFactory(PlaceFactory)44 organization = factory.SubFactory(OrganizationFactory)45 class Meta:46 model = organization_models.Facility47 django_get_or_create = ['name', 'place', 'organization']48class TaskFactory(factory.DjangoModelFactory):49 class Meta:50 model = organization_models.Task51 name = factory.Sequence(lambda n: 'Task ' + str(n))52 description = factory.Sequence(lambda n: 'task ' + str(n))53 facility = factory.SubFactory(FacilityFactory)54class ShiftFactory(factory.DjangoModelFactory):55 class Meta:56 model = scheduler_models.Shift57 task = factory.SubFactory(TaskFactory)58 facility = factory.SubFactory(FacilityFactory)59 starting_time = datetime(2016, 2, 13, 19, 0)60 ending_time = datetime(2016, 2, 13, 20, 0)61 slots = 1062class UserFactory(factory.DjangoModelFactory):63 class Meta:64 model = User65 username = FuzzyText(length=10, chars=string.ascii_letters, prefix='')66 first_name = FuzzyText(length=10, chars=string.ascii_letters, prefix='')67 last_name = FuzzyText(length=10, chars=string.ascii_letters, prefix='')68 password = factory.PostGenerationMethodCall('set_password', 'defaultpassword')69 email = factory.LazyAttribute(lambda o: '%s@example.com' % o.last_name)70class UserAccountFactory(factory.DjangoModelFactory):71 class Meta:72 model = account_models.UserAccount73 user = factory.SubFactory(UserFactory)74class ShiftHelperFactory(factory.DjangoModelFactory):75 class Meta:76 model = scheduler_models.ShiftHelper77 django_get_or_create = ['shift']78 user_account = factory.SubFactory(UserAccountFactory)...
catalogue.py
Source:catalogue.py
1# coding=utf-82import factory3from oscar.core.loading import get_model4__all__ = [5 'ProductClassFactory', 'ProductFactory',6 'CategoryFactory', 'ProductCategoryFactory',7 'ProductAttributeFactory', 'AttributeOptionGroupFactory',8 'OptionFactory', 'AttributeOptionFactory',9 'ProductAttributeValueFactory', 'ProductReviewFactory',10 'ProductImageFactory'11]12class ProductClassFactory(factory.DjangoModelFactory):13 name = "Books"14 requires_shipping = True15 track_stock = True16 class Meta:17 model = get_model('catalogue', 'ProductClass')18class ProductFactory(factory.DjangoModelFactory):19 class Meta:20 model = get_model('catalogue', 'Product')21 structure = Meta.model.STANDALONE22 upc = factory.Sequence(lambda n: '978080213020%d' % n)23 title = "A confederacy of dunces"24 product_class = factory.SubFactory(ProductClassFactory)25 stockrecords = factory.RelatedFactory(26 'oscar.test.factories.StockRecordFactory', 'product')27 categories = factory.RelatedFactory(28 'oscar.test.factories.ProductCategoryFactory', 'product')29class CategoryFactory(factory.DjangoModelFactory):30 name = factory.Sequence(lambda n: 'Category %d' % n)31 # Very naive handling of treebeard node fields. Works though!32 depth = 133 path = factory.Sequence(lambda n: '%04d' % n)34 class Meta:35 model = get_model('catalogue', 'Category')36class ProductCategoryFactory(factory.DjangoModelFactory):37 category = factory.SubFactory(CategoryFactory)38 class Meta:39 model = get_model('catalogue', 'ProductCategory')40class ProductAttributeFactory(factory.DjangoModelFactory):41 code = name = 'weight'42 product_class = factory.SubFactory(ProductClassFactory)43 type = "float"44 class Meta:45 model = get_model('catalogue', 'ProductAttribute')46class OptionFactory(factory.DjangoModelFactory):47 class Meta:48 model = get_model('catalogue', 'Option')49 name = 'example option'50 code = 'example'51 type = Meta.model.TEXT52 required = False53class AttributeOptionFactory(factory.DjangoModelFactory):54 # Ideally we'd get_or_create a AttributeOptionGroup here, but I'm not55 # aware of how to not create a unique option group for each call of the56 # factory57 option = factory.Sequence(lambda n: 'Option %d' % n)58 class Meta:59 model = get_model('catalogue', 'AttributeOption')60class AttributeOptionGroupFactory(factory.DjangoModelFactory):61 name = 'Grüppchen'62 class Meta:63 model = get_model('catalogue', 'AttributeOptionGroup')64class ProductAttributeValueFactory(factory.DjangoModelFactory):65 attribute = factory.SubFactory(ProductAttributeFactory)66 product = factory.SubFactory(ProductFactory)67 class Meta:68 model = get_model('catalogue', 'ProductAttributeValue')69class ProductReviewFactory(factory.DjangoModelFactory):70 score = 571 product = factory.SubFactory(ProductFactory, stockrecords=[])72 class Meta:73 model = get_model('reviews', 'ProductReview')74class ProductImageFactory(factory.DjangoModelFactory):75 product = factory.SubFactory(ProductFactory, stockrecords=[])76 original = factory.django.ImageField(width=100, height=200, filename='test_image.jpg')77 class Meta:...
factory.py
Source:factory.py
1import datetime2import random3import factory4import pytz5from django.utils.text import slugify6from factory import django, fuzzy7from faker import Faker8from title_api.models import Category, Genre, Title, Review, Comment9from users_api.factory import YamdbUserFactory10class CategoryFactory(django.DjangoModelFactory):11 class Meta:12 model = Category13 name = factory.Sequence(lambda n: f'Category-{n}')14 @factory.lazy_attribute15 def slug(self):16 return slugify(self.name)17class GenreFactory(django.DjangoModelFactory):18 class Meta:19 model = Genre20 name = factory.Sequence(lambda n: f'Genre-{n}')21 @factory.lazy_attribute22 def slug(self):23 return slugify(self.name)24class TitleFactory(django.DjangoModelFactory):25 category = factory.SubFactory(CategoryFactory)26 @factory.lazy_attribute27 def name(self):28 fake = Faker(locale='en-US')29 return fake.catch_phrase()30 @factory.lazy_attribute31 def year(self):32 fake = Faker()33 return fake.year()34 @factory.lazy_attribute35 def description(self):36 fake = Faker()37 sentences = random.randint(2, 7)38 return ' '.join(fake.paragraphs(nb=sentences))39 @factory.post_generation40 def genre(self, create, extracted, **kwargs):41 if not create:42 return43 if extracted:44 for one_genre in extracted:45 if random.random() < 0.3:46 self.genre.add(one_genre)47 class Meta:48 model = Title49class ReviewFactory(django.DjangoModelFactory):50 author = factory.SubFactory(YamdbUserFactory)51 score = fuzzy.FuzzyInteger(1, 10)52 title = factory.SubFactory(TitleFactory)53 @factory.lazy_attribute54 def text(self):55 fake = Faker()56 sentences = random.randint(2, 12)57 return ' '.join(fake.paragraphs(nb=sentences))58 @factory.lazy_attribute59 def pub_date(self):60 fake = Faker()61 from_date = datetime.datetime.strptime(str(self.title.year), '%Y')62 return fake.date_time_ad(63 start_datetime=from_date,64 end_datetime='now',65 tzinfo=pytz.UTC,66 )67 class Meta:68 model = Review69class CommentsFactory(django.DjangoModelFactory):70 author = factory.SubFactory(YamdbUserFactory)71 review = factory.SubFactory(ReviewFactory)72 @factory.lazy_attribute73 def text(self):74 fake = Faker()75 sentences = random.randint(1, 5)76 return ' '.join(fake.paragraphs(nb=sentences))77 @factory.lazy_attribute78 def pub_date(self):79 fake = Faker()80 from_datetime = self.review.pub_date81 return fake.date_time_ad(82 start_datetime=from_datetime,83 end_datetime='now',84 tzinfo=pytz.UTC,85 )86 class Meta:...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of ['chromium', 'firefox', 'webkit']) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example-${browserType}.png` });8 await browser.close();9 }10})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const playwright = require('playwright');18(async () => {19 for (const browserType of BROWSER_TYPES) {20 const browser = await playwright[browserType].launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.screenshot({ path: `example-${browserType}.png` });24 await browser.close();25 }26})();27const playwright = require('playwright');28(async () => {29 const browser = await playwright.chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 await page.screenshot({ path: `example.png` });33 await browser.close();34})();35const playwright = require('playwright');36(async () => {37 const browser = await playwright['chromium'].launch();38 const context = await browser.newContext();39 const page = await context.newPage();40 await page.screenshot({ path: `example.png` });41 await browser.close();42})();43const playwright = require('playwright');44(async () => {45 const browser = await playwright['chromium'].launch();46 const context = await browser.newContext();47 const page = await context.newPage();48 await page.screenshot({ path: `example.png`
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const context = await browser.newContext();12 const page = await context.newPage();13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {38 const browser = await chromium.launch();39 const context = await browser.newContext();40 const page = await context.newPage();41 await browser.close();42})();43const { chromium } = require('playwright');44(async () => {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const playwright = require('playwright');10(async () => {11 const browser = await playwright.chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const playwright = require('playwright');26(async () => {27 const browser = await playwright.chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch({ headless: false });36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: `example.png` });39 await browser.close();40})();41const playwright = require('playwright');42(async () => {43 const browser = await playwright.chromium.launch({ headless: false });
Using AI Code Generation
1const {chromium, webkit, firefox} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const {chromium, webkit, firefox} = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const {chromium, webkit, firefox} = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const {chromium, webkit, firefox} = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const {chromium, webkit, firefox} = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const {chromium, webkit, firefox} = require('playwright');42(async () => {
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.webkit.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: 'example.png' });6 await browser.close();7})();8const { webkit } = require('playwright');9(async () => {10 const browser = await webkit.launch();11 const page = await browser.newPage();12 await page.screenshot({ path: 'example.png' });13 await browser.close();14})();15const { webkit } = require('playwright');16(async () => {17 const browser = await webkit.launch();18 const page = await browser.newPage();19 await page.screenshot({ path: 'example.png' });20 await browser.close();21})();22const { test, expect } = require('@playwright/test');23test('basic test', async ({ page }) => {24 const title = page.locator('.navbar__inner .navbar__title');25 await expect(title).toHaveText('Playwright');26});27const { test, expect } = require('@playwright/test');28test('basic test', async ({ page }) => {29 const title = page.locator('.navbar__inner .navbar__title');30 await expect(title).toHaveText('Playwright');31});32const { test, expect } = require('@playwright/test');33test('basic test', async ({ page }) => {34 const title = page.locator('.navbar__inner .navbar__title');
Using AI Code Generation
1const { chromium } = require('playwright');2const { createPlaywright } = require('playwright-core/lib/server/browserType');3const playwright = createPlaywright([chromium]);4(async () => {5 const browser = await playwright.chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11 at Object.error (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/protocol.js:185:12)12 at CDPSession.dispatch (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/protocol.js:69:46)13 at CDPSession._onMessage (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/protocol.js:34:14)14 at Connection.dispatch (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/Connection.js:209:12)15 at WebSocketTransport._ws.addEventListener.event (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/Connection.js:165:22)16 at WebSocketTransport._ws.addEventListener.event (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/Connection.js:163:47)17 at WebSocket.onMessage (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/WebSocketTransport.js:43:14)18 at WebSocket.onMessage (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/lib/server/cjs/protocol/WebSocketTransport.js:17:59)19 at WebSocket.emit (events.js:315:20)20 at Receiver.receiverOnMessage (/Users/raghavendra.kodali/Documents/Playwright/playwright-core/node_modules/ws/lib/websocket.js:800:20)
Using AI Code Generation
1const { chromium } = require('playwright');2const { createPlaywrightInternal } = require('playwright/lib/server/playwright');3const playwright = createPlaywrightInternal();4(async () => {5 const browser = await playwright.chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 await browser.close();10})();11const { chromium } = require('playwright');12const { createPlaywright } = require('playwright/lib/server/playwright');13const playwright = createPlaywright();14(async () => {15 const browser = await playwright.chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.screenshot({ path: 'example.png' });19 await browser.close();20})();21const { chromium } = require('playwright');22const { createPlaywright } = require('playwright/lib/server/playwright');23const playwright = createPlaywright();24(async () => {25 const browser = await playwright.chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.screenshot({ path: 'example.png' });29 await browser.close();30})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!