Best JavaScript code snippet using cypress
loaddata.py
Source:loaddata.py
...24except ImportError:25 has_bz2 = False26READ_STDIN = '-'27class Command(BaseCommand):28 help = 'Installs the named fixture(s) in the database.'29 missing_args_message = (30 "No database fixture specified. Please provide the path of at least "31 "one fixture in the command line."32 )33 def add_arguments(self, parser):34 parser.add_argument('args', metavar='fixture', nargs='+', help='Fixture labels.')35 parser.add_argument(36 '--database', default=DEFAULT_DB_ALIAS,37 help='Nominates a specific database to load fixtures into. Defaults to the "default" database.',38 )39 parser.add_argument(40 '--app', dest='app_label',41 help='Only look for fixtures in the specified app.',42 )43 parser.add_argument(44 '--ignorenonexistent', '-i', action='store_true', dest='ignore',45 help='Ignores entries in the serialized data for fields that do not '46 'currently exist on the model.',47 )48 parser.add_argument(49 '-e', '--exclude', action='append', default=[],50 help='An app_label or app_label.ModelName to exclude. Can be used multiple times.',51 )52 parser.add_argument(53 '--format',54 help='Format of serialized data when reading from stdin.',55 )56 def handle(self, *fixture_labels, **options):57 self.ignore = options['ignore']58 self.using = options['database']59 self.app_label = options['app_label']60 self.verbosity = options['verbosity']61 self.excluded_models, self.excluded_apps = parse_apps_and_model_labels(options['exclude'])62 self.format = options['format']63 with transaction.atomic(using=self.using):64 self.loaddata(fixture_labels)65 # Close the DB connection -- unless we're still in a transaction. This66 # is required as a workaround for an edge case in MySQL: if the same67 # connection is used to create tables, load data, and query, the query68 # can return incorrect results. See Django #7572, MySQL #37735.69 if transaction.get_autocommit(self.using):70 connections[self.using].close()71 def loaddata(self, fixture_labels):72 connection = connections[self.using]73 # Keep a count of the installed objects and fixtures74 self.fixture_count = 075 self.loaded_object_count = 076 self.fixture_object_count = 077 self.models = set()78 self.serialization_formats = serializers.get_public_serializer_formats()79 # Forcing binary mode may be revisited after dropping Python 2 support (see #22399)80 self.compression_formats = {81 None: (open, 'rb'),82 'gz': (gzip.GzipFile, 'rb'),83 'zip': (SingleZipReader, 'r'),84 'stdin': (lambda *args: sys.stdin, None),85 }86 if has_bz2:87 self.compression_formats['bz2'] = (bz2.BZ2File, 'r')88 # Django's test suite repeatedly tries to load initial_data fixtures89 # from apps that don't have any fixtures. Because disabling constraint90 # checks can be expensive on some database (especially MSSQL), bail91 # out early if no fixtures are found.92 for fixture_label in fixture_labels:93 if self.find_fixtures(fixture_label):94 break95 else:96 return97 with connection.constraint_checks_disabled():98 self.objs_with_deferred_fields = []99 for fixture_label in fixture_labels:100 self.load_label(fixture_label)101 for obj in self.objs_with_deferred_fields:102 obj.save_deferred_fields(using=self.using)103 # Since we disabled constraint checks, we must manually check for104 # any invalid keys that might have been added105 table_names = [model._meta.db_table for model in self.models]106 try:107 connection.check_constraints(table_names=table_names)108 except Exception as e:109 e.args = ("Problem installing fixtures: %s" % e,)110 raise111 # If we found even one object in a fixture, we need to reset the112 # database sequences.113 if self.loaded_object_count > 0:114 sequence_sql = connection.ops.sequence_reset_sql(no_style(), self.models)115 if sequence_sql:116 if self.verbosity >= 2:117 self.stdout.write("Resetting sequences\n")118 with connection.cursor() as cursor:119 for line in sequence_sql:120 cursor.execute(line)121 if self.verbosity >= 1:122 if self.fixture_object_count == self.loaded_object_count:123 self.stdout.write(124 "Installed %d object(s) from %d fixture(s)"125 % (self.loaded_object_count, self.fixture_count)126 )127 else:128 self.stdout.write(129 "Installed %d object(s) (of %d) from %d fixture(s)"130 % (self.loaded_object_count, self.fixture_object_count, self.fixture_count)131 )132 def load_label(self, fixture_label):133 """Load fixtures files for a given label."""134 show_progress = self.verbosity >= 3135 for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label):136 _, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file))137 open_method, mode = self.compression_formats[cmp_fmt]138 fixture = open_method(fixture_file, mode)139 try:140 self.fixture_count += 1141 objects_in_fixture = 0142 loaded_objects_in_fixture = 0143 if self.verbosity >= 2:...
process.py
Source:process.py
1# Copyright 2015 Red Hat, Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may4# not use this file except in compliance with the License. You may obtain5# a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the12# License for the specific language governing permissions and limitations13# under the License.14import datetime15from distutils import spawn16import os17import re18import signal19import fixtures20from neutronclient.common import exceptions as nc_exc21from neutronclient.v2_0 import client22from oslo_utils import fileutils23from neutron.agent.linux import async_process24from neutron.agent.linux import ip_lib25from neutron.agent.linux import utils26from neutron.common import utils as common_utils27from neutron.tests import base28from neutron.tests.common import net_helpers29from neutron.tests.fullstack import base as fullstack_base30class ProcessFixture(fixtures.Fixture):31 def __init__(self, test_name, process_name, exec_name, config_filenames,32 namespace=None, kill_signal=signal.SIGKILL):33 super(ProcessFixture, self).__init__()34 self.test_name = test_name35 self.process_name = process_name36 self.exec_name = exec_name37 self.config_filenames = config_filenames38 self.process = None39 self.kill_signal = kill_signal40 self.namespace = namespace41 def _setUp(self):42 self.start()43 self.addCleanup(self.stop)44 def start(self):45 test_name = base.sanitize_log_path(self.test_name)46 log_dir = os.path.join(fullstack_base.DEFAULT_LOG_DIR, test_name)47 fileutils.ensure_tree(log_dir, mode=0o755)48 timestamp = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S-%f")49 log_file = "%s--%s.log" % (self.process_name, timestamp)50 cmd = [spawn.find_executable(self.exec_name),51 '--log-dir', log_dir,52 '--log-file', log_file]53 for filename in self.config_filenames:54 cmd += ['--config-file', filename]55 run_as_root = bool(self.namespace)56 self.process = async_process.AsyncProcess(57 cmd, run_as_root=run_as_root, namespace=self.namespace58 )59 self.process.start(block=True)60 def stop(self):61 try:62 self.process.stop(block=True, kill_signal=self.kill_signal)63 except async_process.AsyncProcessException as e:64 if "Process is not running" not in str(e):65 raise66class RabbitmqEnvironmentFixture(fixtures.Fixture):67 def __init__(self, host="127.0.0.1"):68 super(RabbitmqEnvironmentFixture, self).__init__()69 self.host = host70 def _setUp(self):71 self.user = common_utils.get_rand_name(prefix='user')72 self.password = common_utils.get_rand_name(prefix='pass')73 self.vhost = common_utils.get_rand_name(prefix='vhost')74 self._execute('add_user', self.user, self.password)75 self.addCleanup(self._execute, 'delete_user', self.user)76 self._execute('add_vhost', self.vhost)77 self.addCleanup(self._execute, 'delete_vhost', self.vhost)78 self._execute('set_permissions', '-p', self.vhost, self.user,79 '.*', '.*', '.*')80 def _execute(self, *args):81 cmd = ['rabbitmqctl']82 cmd.extend(args)83 utils.execute(cmd, run_as_root=True)84class NeutronServerFixture(fixtures.Fixture):85 NEUTRON_SERVER = "neutron-server"86 def __init__(self, env_desc, host_desc,87 test_name, neutron_cfg_fixture, plugin_cfg_fixture):88 super(NeutronServerFixture, self).__init__()89 self.env_desc = env_desc90 self.host_desc = host_desc91 self.test_name = test_name92 self.neutron_cfg_fixture = neutron_cfg_fixture93 self.plugin_cfg_fixture = plugin_cfg_fixture94 def _setUp(self):95 config_filenames = [self.neutron_cfg_fixture.filename,96 self.plugin_cfg_fixture.filename]97 self.process_fixture = self.useFixture(ProcessFixture(98 test_name=self.test_name,99 process_name=self.NEUTRON_SERVER,100 exec_name=self.NEUTRON_SERVER,101 config_filenames=config_filenames,102 kill_signal=signal.SIGTERM))103 common_utils.wait_until_true(self.server_is_live)104 def server_is_live(self):105 try:106 self.client.list_networks()107 return True108 except nc_exc.NeutronClientException:109 return False110 @property111 def client(self):112 url = ("http://127.0.0.1:%s" %113 self.neutron_cfg_fixture.config.DEFAULT.bind_port)114 return client.Client(auth_strategy="noauth", endpoint_url=url)115class OVSAgentFixture(fixtures.Fixture):116 NEUTRON_OVS_AGENT = "neutron-openvswitch-agent"117 def __init__(self, env_desc, host_desc,118 test_name, neutron_cfg_fixture, agent_cfg_fixture):119 super(OVSAgentFixture, self).__init__()120 self.env_desc = env_desc121 self.host_desc = host_desc122 self.test_name = test_name123 self.neutron_cfg_fixture = neutron_cfg_fixture124 self.neutron_config = self.neutron_cfg_fixture.config125 self.agent_cfg_fixture = agent_cfg_fixture126 self.agent_config = agent_cfg_fixture.config127 def _setUp(self):128 self.br_int = self.useFixture(129 net_helpers.OVSBridgeFixture(130 self.agent_cfg_fixture.get_br_int_name())).bridge131 config_filenames = [self.neutron_cfg_fixture.filename,132 self.agent_cfg_fixture.filename]133 self.process_fixture = self.useFixture(ProcessFixture(134 test_name=self.test_name,135 process_name=self.NEUTRON_OVS_AGENT,136 exec_name=spawn.find_executable(137 'ovs_agent.py',138 path=os.path.join(base.ROOTDIR, 'common', 'agents')),139 config_filenames=config_filenames,140 kill_signal=signal.SIGTERM))141class LinuxBridgeAgentFixture(fixtures.Fixture):142 NEUTRON_LINUXBRIDGE_AGENT = "neutron-linuxbridge-agent"143 def __init__(self, env_desc, host_desc, test_name,144 neutron_cfg_fixture, agent_cfg_fixture,145 namespace=None):146 super(LinuxBridgeAgentFixture, self).__init__()147 self.env_desc = env_desc148 self.host_desc = host_desc149 self.test_name = test_name150 self.neutron_cfg_fixture = neutron_cfg_fixture151 self.neutron_config = self.neutron_cfg_fixture.config152 self.agent_cfg_fixture = agent_cfg_fixture153 self.agent_config = agent_cfg_fixture.config154 self.namespace = namespace155 def _setUp(self):156 config_filenames = [self.neutron_cfg_fixture.filename,157 self.agent_cfg_fixture.filename]158 self.process_fixture = self.useFixture(159 ProcessFixture(160 test_name=self.test_name,161 process_name=self.NEUTRON_LINUXBRIDGE_AGENT,162 exec_name=self.NEUTRON_LINUXBRIDGE_AGENT,163 config_filenames=config_filenames,164 namespace=self.namespace165 )166 )167class L3AgentFixture(fixtures.Fixture):168 NEUTRON_L3_AGENT = "neutron-l3-agent"169 def __init__(self, env_desc, host_desc, test_name,170 neutron_cfg_fixture, l3_agent_cfg_fixture,171 namespace=None):172 super(L3AgentFixture, self).__init__()173 self.env_desc = env_desc174 self.host_desc = host_desc175 self.test_name = test_name176 self.neutron_cfg_fixture = neutron_cfg_fixture177 self.l3_agent_cfg_fixture = l3_agent_cfg_fixture178 self.namespace = namespace179 def _setUp(self):180 self.plugin_config = self.l3_agent_cfg_fixture.config181 config_filenames = [self.neutron_cfg_fixture.filename,182 self.l3_agent_cfg_fixture.filename]183 self.process_fixture = self.useFixture(184 ProcessFixture(185 test_name=self.test_name,186 process_name=self.NEUTRON_L3_AGENT,187 exec_name=spawn.find_executable(188 'l3_agent.py',189 path=os.path.join(base.ROOTDIR, 'common', 'agents')),190 config_filenames=config_filenames,191 namespace=self.namespace192 )193 )194 def get_namespace_suffix(self):195 return self.plugin_config.DEFAULT.test_namespace_suffix196class DhcpAgentFixture(fixtures.Fixture):197 NEUTRON_DHCP_AGENT = "neutron-dhcp-agent"198 def __init__(self, env_desc, host_desc, test_name,199 neutron_cfg_fixture, agent_cfg_fixture, namespace=None):200 super(DhcpAgentFixture, self).__init__()201 self.env_desc = env_desc202 self.host_desc = host_desc203 self.test_name = test_name204 self.neutron_cfg_fixture = neutron_cfg_fixture205 self.agent_cfg_fixture = agent_cfg_fixture206 self.namespace = namespace207 def _setUp(self):208 self.plugin_config = self.agent_cfg_fixture.config209 config_filenames = [self.neutron_cfg_fixture.filename,210 self.agent_cfg_fixture.filename]211 self.process_fixture = self.useFixture(212 ProcessFixture(213 test_name=self.test_name,214 process_name=self.NEUTRON_DHCP_AGENT,215 exec_name=spawn.find_executable(216 'fullstack_dhcp_agent.py',217 path=os.path.join(base.ROOTDIR, 'common', 'agents')),218 config_filenames=config_filenames,219 namespace=self.namespace220 )221 )222 self.dhcp_namespace_pattern = re.compile(223 r"qdhcp-[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}%s" %224 self.get_namespace_suffix())225 self.addCleanup(self.clean_dhcp_namespaces)226 def get_agent_hostname(self):227 return self.neutron_cfg_fixture.config['DEFAULT']['host']228 def get_namespace_suffix(self):229 return self.plugin_config.DEFAULT.test_namespace_suffix230 def kill(self):231 self.process_fixture.stop()232 self.clean_dhcp_namespaces()233 def clean_dhcp_namespaces(self):234 """Delete all DHCP namespaces created by DHCP agent.235 In some tests for DHCP agent HA agents are killed when handling DHCP236 service for network(s). In such case DHCP namespace is not deleted by237 DHCP agent and such namespaces are found and deleted using agent's238 namespace suffix.239 """240 ip_wrapper = ip_lib.IPWrapper()241 for namespace in ip_wrapper.get_namespaces():242 if self.dhcp_namespace_pattern.match(namespace):243 try:244 ip_wrapper.netns.delete(namespace)245 except RuntimeError:246 # Continue cleaning even if namespace deletions fails...
syncdata.py
Source:syncdata.py
...20class SyncDataError(Exception):21 pass22class Command(BaseCommand):23 """ syncdata command """24 help = 'Makes the current database have the same data as the fixture(s), no more, no less.'25 args = "fixture [fixture ...]"26 def add_arguments(self, parser):27 super(Command, self).add_arguments(parser)28 parser.add_argument(29 '--skip-remove', action='store_false', dest='remove', default=True,30 help='Avoid remove any object from db',31 )32 parser.add_argument(33 '--database', default=DEFAULT_DB_ALIAS,34 help='Nominates a specific database to load fixtures into. Defaults to the "default" database.',35 )36 parser.add_argument(37 'fixture_labels', nargs='?', type=str,38 help='Specify the fixture label (comma separated)',...
test_exporter_fixtures.py
Source:test_exporter_fixtures.py
1# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors2# MIT License. See license.txt3from __future__ import unicode_literals4import frappe5import frappe.defaults6from frappe.core.doctype.data_import.data_import import export_csv7import unittest8import os9class TestDataImportFixtures(unittest.TestCase):10 def setUp(self):11 pass12 #start test for Client Script13 def test_Custom_Script_fixture_simple(self):14 fixture = "Client Script"15 path = frappe.scrub(fixture) + "_original_style.csv"16 export_csv(fixture, path)17 self.assertTrue(True)18 os.remove(path)19 def test_Custom_Script_fixture_simple_name_equal_default(self):20 fixture = ["Client Script", {"name":["Item"]}]21 path = frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv"22 export_csv(fixture, path)23 self.assertTrue(True)24 os.remove(path)25 def test_Custom_Script_fixture_simple_name_equal(self):26 fixture = ["Client Script", {"name":["Item"],"op":"="}]27 path = frappe.scrub(fixture[0]) + "_simple_name_equal.csv"28 export_csv(fixture, path)29 self.assertTrue(True)30 os.remove(path)31 def test_Custom_Script_fixture_simple_name_not_equal(self):32 fixture = ["Client Script", {"name":["Item"],"op":"!="}]33 path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"34 export_csv(fixture, path)35 self.assertTrue(True)36 os.remove(path)37 #without [] around the name...38 def test_Custom_Script_fixture_simple_name_at_least_equal(self):39 fixture = ["Client Script", {"name":"Item-Cli"}]40 path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"41 export_csv(fixture, path)42 self.assertTrue(True)43 os.remove(path)44 def test_Custom_Script_fixture_multi_name_equal(self):45 fixture = ["Client Script", {"name":["Item", "Customer"],"op":"="}]46 path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv"47 export_csv(fixture, path)48 self.assertTrue(True)49 os.remove(path)50 def test_Custom_Script_fixture_multi_name_not_equal(self):51 fixture = ["Client Script", {"name":["Item", "Customer"],"op":"!="}]52 path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"53 export_csv(fixture, path)54 self.assertTrue(True)55 os.remove(path)56 def test_Custom_Script_fixture_empty_object(self):57 fixture = ["Client Script", {}]58 path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"59 export_csv(fixture, path)60 self.assertTrue(True)61 os.remove(path)62 def test_Custom_Script_fixture_just_list(self):63 fixture = ["Client Script"]64 path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"65 export_csv(fixture, path)66 self.assertTrue(True)67 os.remove(path)68 # Client Script regular expression69 def test_Custom_Script_fixture_rex_no_flags(self):70 fixture = ["Client Script", {"name":r"^[i|A]"}]71 path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv"72 export_csv(fixture, path)73 self.assertTrue(True)74 os.remove(path)75 def test_Custom_Script_fixture_rex_with_flags(self):76 fixture = ["Client Script", {"name":r"^[i|A]", "flags":"L,M"}]77 path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv"78 export_csv(fixture, path)79 self.assertTrue(True)80 os.remove(path)81 #start test for Custom Field82 def test_Custom_Field_fixture_simple(self):83 fixture = "Custom Field"84 path = frappe.scrub(fixture) + "_original_style.csv"85 export_csv(fixture, path)86 self.assertTrue(True)87 os.remove(path)88 def test_Custom_Field_fixture_simple_name_equal_default(self):89 fixture = ["Custom Field", {"name":["Item-vat"]}]90 path = frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv"91 export_csv(fixture, path)92 self.assertTrue(True)93 os.remove(path)94 def test_Custom_Field_fixture_simple_name_equal(self):95 fixture = ["Custom Field", {"name":["Item-vat"],"op":"="}]96 path = frappe.scrub(fixture[0]) + "_simple_name_equal.csv"97 export_csv(fixture, path)98 self.assertTrue(True)99 os.remove(path)100 def test_Custom_Field_fixture_simple_name_not_equal(self):101 fixture = ["Custom Field", {"name":["Item-vat"],"op":"!="}]102 path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"103 export_csv(fixture, path)104 self.assertTrue(True)105 os.remove(path)106 #without [] around the name...107 def test_Custom_Field_fixture_simple_name_at_least_equal(self):108 fixture = ["Custom Field", {"name":"Item-va"}]109 path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"110 export_csv(fixture, path)111 self.assertTrue(True)112 os.remove(path)113 def test_Custom_Field_fixture_multi_name_equal(self):114 fixture = ["Custom Field", {"name":["Item-vat", "Bin-vat"],"op":"="}]115 path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv"116 export_csv(fixture, path)117 self.assertTrue(True)118 os.remove(path)119 def test_Custom_Field_fixture_multi_name_not_equal(self):120 fixture = ["Custom Field", {"name":["Item-vat", "Bin-vat"],"op":"!="}]121 path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"122 export_csv(fixture, path)123 self.assertTrue(True)124 os.remove(path)125 def test_Custom_Field_fixture_empty_object(self):126 fixture = ["Custom Field", {}]127 path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"128 export_csv(fixture, path)129 self.assertTrue(True)130 os.remove(path)131 def test_Custom_Field_fixture_just_list(self):132 fixture = ["Custom Field"]133 path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"134 export_csv(fixture, path)135 self.assertTrue(True)136 os.remove(path)137 # Custom Field regular expression138 def test_Custom_Field_fixture_rex_no_flags(self):139 fixture = ["Custom Field", {"name":r"^[r|L]"}]140 path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv"141 export_csv(fixture, path)142 self.assertTrue(True)143 os.remove(path)144 def test_Custom_Field_fixture_rex_with_flags(self):145 fixture = ["Custom Field", {"name":r"^[i|A]", "flags":"L,M"}]146 path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv"147 export_csv(fixture, path)148 self.assertTrue(True)149 os.remove(path)150 #start test for Doctype151 def test_Doctype_fixture_simple(self):152 fixture = "ToDo"153 path = "Doctype_" + frappe.scrub(fixture) + "_original_style_should_be_all.csv"154 export_csv(fixture, path)155 self.assertTrue(True)156 os.remove(path)157 def test_Doctype_fixture_simple_name_equal_default(self):158 fixture = ["ToDo", {"name":["TDI00000008"]}]159 path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv"160 export_csv(fixture, path)161 self.assertTrue(True)162 os.remove(path)163 def test_Doctype_fixture_simple_name_equal(self):164 fixture = ["ToDo", {"name":["TDI00000002"],"op":"="}]165 path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal.csv"166 export_csv(fixture, path)167 self.assertTrue(True)168 os.remove(path)169 def test_Doctype_simple_name_not_equal(self):170 fixture = ["ToDo", {"name":["TDI00000002"],"op":"!="}]171 path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"172 export_csv(fixture, path)173 self.assertTrue(True)174 os.remove(path)175 #without [] around the name...176 def test_Doctype_fixture_simple_name_at_least_equal(self):177 fixture = ["ToDo", {"name":"TDI"}]178 path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"179 export_csv(fixture, path)180 self.assertTrue(True)181 os.remove(path)182 def test_Doctype_multi_name_equal(self):183 fixture = ["ToDo", {"name":["TDI00000002", "TDI00000008"],"op":"="}]184 path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_equal.csv"185 export_csv(fixture, path)186 self.assertTrue(True)187 os.remove(path)188 def test_Doctype_multi_name_not_equal(self):189 fixture = ["ToDo", {"name":["TDI00000002", "TDI00000008"],"op":"!="}]190 path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"191 export_csv(fixture, path)192 self.assertTrue(True)193 os.remove(path)194 def test_Doctype_fixture_empty_object(self):195 fixture = ["ToDo", {}]196 path = "Doctype_" + frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"197 export_csv(fixture, path)198 self.assertTrue(True)199 os.remove(path)200 def test_Doctype_fixture_just_list(self):201 fixture = ["ToDo"]202 path = "Doctype_" + frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"203 export_csv(fixture, path)204 self.assertTrue(True)205 os.remove(path)206 # Doctype regular expression207 def test_Doctype_fixture_rex_no_flags(self):208 fixture = ["ToDo", {"name":r"^TDi"}]209 path = "Doctype_" + frappe.scrub(fixture[0]) + "_rex_no_flags_should_be_all.csv"210 export_csv(fixture, path)211 self.assertTrue(True)212 os.remove(path)213 def test_Doctype_fixture_rex_with_flags(self):214 fixture = ["ToDo", {"name":r"^TDi", "flags":"L,M"}]215 path = "Doctype_" + frappe.scrub(fixture[0]) + "_rex_with_flags_should_be_none.csv"216 export_csv(fixture, path)217 self.assertTrue(True)...
fixture_tables.py
Source:fixture_tables.py
1"""A copy of Django 1.3.0's stock loaddata.py, adapted so that, instead of2loading any data, it returns the tables referenced by a set of fixtures so we3can truncate them (and no others) quickly after we're finished with them."""4import os5import gzip6import zipfile7from itertools import product8from django.conf import settings9from django.core import serializers10from django.db import router, DEFAULT_DB_ALIAS11from django.db.models import get_apps12try:13 import bz214 has_bz2 = True15except ImportError:16 has_bz2 = False17def tables_used_by_fixtures(fixture_labels, using=DEFAULT_DB_ALIAS):18 """Act like Django's stock loaddata command, but, instead of loading data,19 return an iterable of the names of the tables into which data would be20 loaded."""21 # Keep a count of the installed objects and fixtures22 fixture_count = 023 loaded_object_count = 024 fixture_object_count = 025 tables = set()26 class SingleZipReader(zipfile.ZipFile):27 def __init__(self, *args, **kwargs):28 zipfile.ZipFile.__init__(self, *args, **kwargs)29 if settings.DEBUG:30 assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."31 def read(self):32 return zipfile.ZipFile.read(self, self.namelist()[0])33 compression_types = {34 None: file,35 'gz': gzip.GzipFile,36 'zip': SingleZipReader37 }38 if has_bz2:39 compression_types['bz2'] = bz2.BZ2File40 app_module_paths = []41 for app in get_apps():42 if hasattr(app, '__path__'):43 # It's a 'models/' subpackage44 for path in app.__path__:45 app_module_paths.append(path)46 else:47 # It's a models.py module48 app_module_paths.append(app.__file__)49 app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]50 for fixture_label in fixture_labels:51 parts = fixture_label.split('.')52 if len(parts) > 1 and parts[-1] in compression_types:53 compression_formats = [parts[-1]]54 parts = parts[:-1]55 else:56 compression_formats = list(compression_types.keys())57 if len(parts) == 1:58 fixture_name = parts[0]59 formats = serializers.get_public_serializer_formats()60 else:61 fixture_name, format = '.'.join(parts[:-1]), parts[-1]62 if format in serializers.get_public_serializer_formats():63 formats = [format]64 else:65 formats = []66 if not formats:67 # stderr.write(style.ERROR("Problem installing fixture '%s': %s is68 # not a known serialization format.\n" % (fixture_name, format)))69 return set()70 if os.path.isabs(fixture_name):71 fixture_dirs = [fixture_name]72 else:73 fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']74 for fixture_dir in fixture_dirs:75 # stdout.write("Checking %s for fixtures...\n" %76 # humanize(fixture_dir))77 label_found = False78 for combo in product([using, None], formats, compression_formats):79 database, format, compression_format = combo80 file_name = '.'.join(81 p for p in [82 fixture_name, database, format, compression_format83 ]84 if p85 )86 # stdout.write("Trying %s for %s fixture '%s'...\n" % \87 # (humanize(fixture_dir), file_name, fixture_name))88 full_path = os.path.join(fixture_dir, file_name)89 open_method = compression_types[compression_format]90 try:91 fixture = open_method(full_path, 'r')92 if label_found:93 fixture.close()94 # stderr.write(style.ERROR("Multiple fixtures named95 # '%s' in %s. Aborting.\n" % (fixture_name,96 # humanize(fixture_dir))))97 return set()98 else:99 fixture_count += 1100 objects_in_fixture = 0101 loaded_objects_in_fixture = 0102 # stdout.write("Installing %s fixture '%s' from %s.\n"103 # % (format, fixture_name, humanize(fixture_dir)))104 try:105 objects = serializers.deserialize(format, fixture, using=using)106 for obj in objects:107 objects_in_fixture += 1108 if router.allow_syncdb(using, obj.object.__class__):109 loaded_objects_in_fixture += 1110 tables.add(111 obj.object.__class__._meta.db_table)112 loaded_object_count += loaded_objects_in_fixture113 fixture_object_count += objects_in_fixture114 label_found = True115 except (SystemExit, KeyboardInterrupt):116 raise117 except Exception:118 fixture.close()119 # stderr.write( style.ERROR("Problem installing120 # fixture '%s': %s\n" % (full_path, ''.join(tra121 # ceback.format_exception(sys.exc_type,122 # sys.exc_value, sys.exc_traceback)))))123 return set()124 fixture.close()125 # If the fixture we loaded contains 0 objects, assume that an126 # error was encountered during fixture loading.127 if objects_in_fixture == 0:128 # stderr.write( style.ERROR("No fixture data found129 # for '%s'. (File format may be invalid.)\n" %130 # (fixture_name)))131 return set()132 except Exception:133 # stdout.write("No %s fixture '%s' in %s.\n" % \ (format,134 # fixture_name, humanize(fixture_dir)))135 pass...
test_fixturesupport.py
Source:test_fixturesupport.py
1# Copyright (c) 2010-2011 testtools developers. See LICENSE for details.2import unittest3from extras import try_import4from testtools import (5 TestCase,6 content,7 content_type,8 )9from testtools.compat import _b, _u10from testtools.testresult.doubles import (11 ExtendedTestResult,12 )13fixtures = try_import('fixtures')14LoggingFixture = try_import('fixtures.tests.helpers.LoggingFixture')15class TestFixtureSupport(TestCase):16 def setUp(self):17 super(TestFixtureSupport, self).setUp()18 if fixtures is None or LoggingFixture is None:19 self.skipTest("Need fixtures")20 def test_useFixture(self):21 fixture = LoggingFixture()22 class SimpleTest(TestCase):23 def test_foo(self):24 self.useFixture(fixture)25 result = unittest.TestResult()26 SimpleTest('test_foo').run(result)27 self.assertTrue(result.wasSuccessful())28 self.assertEqual(['setUp', 'cleanUp'], fixture.calls)29 def test_useFixture_cleanups_raise_caught(self):30 calls = []31 def raiser(ignored):32 calls.append('called')33 raise Exception('foo')34 fixture = fixtures.FunctionFixture(lambda:None, raiser)35 class SimpleTest(TestCase):36 def test_foo(self):37 self.useFixture(fixture)38 result = unittest.TestResult()39 SimpleTest('test_foo').run(result)40 self.assertFalse(result.wasSuccessful())41 self.assertEqual(['called'], calls)42 def test_useFixture_details_captured(self):43 class DetailsFixture(fixtures.Fixture):44 def setUp(self):45 fixtures.Fixture.setUp(self)46 self.addCleanup(delattr, self, 'content')47 self.content = [_b('content available until cleanUp')]48 self.addDetail('content',49 content.Content(content_type.UTF8_TEXT, self.get_content))50 def get_content(self):51 return self.content52 fixture = DetailsFixture()53 class SimpleTest(TestCase):54 def test_foo(self):55 self.useFixture(fixture)56 # Add a colliding detail (both should show up)57 self.addDetail('content',58 content.Content(content_type.UTF8_TEXT, lambda:[_b('foo')]))59 result = ExtendedTestResult()60 SimpleTest('test_foo').run(result)61 self.assertEqual('addSuccess', result._events[-2][0])62 details = result._events[-2][2]63 self.assertEqual(['content', 'content-1'], sorted(details.keys()))64 self.assertEqual('foo', details['content'].as_text())65 self.assertEqual('content available until cleanUp',66 details['content-1'].as_text())67 def test_useFixture_multiple_details_captured(self):68 class DetailsFixture(fixtures.Fixture):69 def setUp(self):70 fixtures.Fixture.setUp(self)71 self.addDetail('aaa', content.text_content("foo"))72 self.addDetail('bbb', content.text_content("bar"))73 fixture = DetailsFixture()74 class SimpleTest(TestCase):75 def test_foo(self):76 self.useFixture(fixture)77 result = ExtendedTestResult()78 SimpleTest('test_foo').run(result)79 self.assertEqual('addSuccess', result._events[-2][0])80 details = result._events[-2][2]81 self.assertEqual(['aaa', 'bbb'], sorted(details))82 self.assertEqual(_u('foo'), details['aaa'].as_text())83 self.assertEqual(_u('bar'), details['bbb'].as_text())84 def test_useFixture_details_captured_from_setUp(self):85 # Details added during fixture set-up are gathered even if setUp()86 # fails with an exception.87 class BrokenFixture(fixtures.Fixture):88 def setUp(self):89 fixtures.Fixture.setUp(self)90 self.addDetail('content', content.text_content("foobar"))91 raise Exception()92 fixture = BrokenFixture()93 class SimpleTest(TestCase):94 def test_foo(self):95 self.useFixture(fixture)96 result = ExtendedTestResult()97 SimpleTest('test_foo').run(result)98 self.assertEqual('addError', result._events[-2][0])99 details = result._events[-2][2]100 self.assertEqual(['content', 'traceback'], sorted(details))101 self.assertEqual('foobar', ''.join(details['content'].iter_text()))102def test_suite():103 from unittest import TestLoader...
conftest.py
Source:conftest.py
...23 if fixture is None or not fixture.is_valid():24 fixture = Application(browser=browser, base_url=web_config["baseUrl"])25 fixture.session.ensure_login(username=web_config["username"], password=web_config["password"])26 return fixture27@pytest.fixture(scope="session")28def db(request):29 db_config = load_config(request.config.getoption("--target"))["db"]30 dbfixture = DbFixture(host=db_config["host"], name=db_config["name"], user=db_config["user"], password=db_config["password"])31 def fin():32 dbfixture.destroy()33 request.addfinalizer(fin)34 return dbfixture35@pytest.fixture(scope="session", autouse=True)36def stop(request):37 def fin():38 fixture.session.ensure_logout()39 fixture.destroy()40 request.addfinalizer(fin)41 return fixture42@pytest.fixture43def check_ui(request):44 return request.config.getoption("--check_ui")45def pytest_addoption(parser):46 parser.addoption("--browser", action="store", default="firefox")47 parser.addoption("--target", action="store", default="target.json")48 parser.addoption("--check_ui", action="store_true")49def pytest_generate_tests(metafunc):...
__init__.py
Source:__init__.py
...14 "ReplicaSetFixture": ReplicaSetFixture,15 "MasterSlaveFixture": MasterSlaveFixture,16 "ShardedClusterFixture": ShardedClusterFixture,17}18def make_fixture(class_name, *args, **kwargs):19 """20 Factory function for creating Fixture instances.21 """22 if class_name not in _FIXTURES:23 raise ValueError("Unknown fixture class '%s'" % (class_name))...
Using AI Code Generation
1describe("My First Test", () => {2 it("Visits the Kitchen Sink", () => {3 cy.contains("type").click();4 cy.url().should("include", "/commands/actions");5 cy.get(".action-email")6 .type("
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe("My First Test", function() {2 it("Visits the Kitchen Sink", function() {3 cy.contains("type").click();4 cy.url().should("include", "/commands/actions");5 cy.get(".action-email")6 .type("
Using AI Code Generation
1describe('My first Test Suite', function() 2{3it('My FirstTest case',function() {4cy.get('.search-keyword').type('ca')5cy.wait(2000)6cy.get('.product:visible').should('have.length',4)7cy.get('.products').as('productLocator')8cy.get('@productLocator').find('.product').should('have.length',4)9cy.get(':nth-child(3) > .product-action > button').click()10cy.get('@productLocator').find('.product').eq(2).contains('ADD TO CART').click().then(function()11{12console.log('sf')13})14})15})
Using AI Code Generation
1describe('My First Test', function() {2 it('Gets, types and asserts', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1describe('My First Test', function() {2 it('Gets, types and asserts', function() {3 cy.get('input[name="username"]')4 .type('test')5 cy.get('input[name="password"]')6 .type('test')7 cy.get('button').click()8 cy.get('h1').contains('Welcome')9 cy.get('h2').contains('test')10 })11})12describe('My First Test', function() {13 it('Gets, types and asserts', function() {14 cy.fixture('user').then((user) => {15 cy.get('input[name="username"]')16 .type(user.username)17 cy.get('input[name="password"]')18 .type(user.password)19 cy.get('button').click()20 cy.get('h1').contains('Welcome')21 cy.get('h2').contains(user.name)22 })23 })24})
Using AI Code Generation
1describe('Cypress Test', function() {2 it('Cypress Test', function() {3 cy.get('.gLFyf').type('cypress.io')4 cy.get('.FPdoLc > center > .gNO89b').click()5 cy.get('.LC20lb > span').click()6 cy.fixture('data.json').then((data) => {7 cy.get('input[name="name"]').type(data.name)8 cy.get('input[name="email"]').type(data.email)9 cy.get('textarea.feedback-input').type(data.message)10 cy.get('input[value="Send"]').click()11 })12 })13})14{
Using AI Code Generation
1describe('Test', () => {2 it('should work', () => {3 cy.fixture('test.json').then((data) => {4 cy.visit(data.url);5 });6 });7});8CypressError: Timed out retrying: cy.visit() failed trying to load:9I am running into the same issue. I have a test that passes the url to visit() as a parameter. When I run the test from the command line, it works
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!