How to use fixture method in storybook-root

Best JavaScript code snippet using storybook-root

loaddata.py

Source:loaddata.py Github

copy

Full Screen

...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:...

Full Screen

Full Screen

process.py

Source:process.py Github

copy

Full Screen

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...

Full Screen

Full Screen

syncdata.py

Source:syncdata.py Github

copy

Full Screen

...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)',...

Full Screen

Full Screen

test_exporter_fixtures.py

Source:test_exporter_fixtures.py Github

copy

Full Screen

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)...

Full Screen

Full Screen

fixture_tables.py

Source:fixture_tables.py Github

copy

Full Screen

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...

Full Screen

Full Screen

test_fixturesupport.py

Source:test_fixturesupport.py Github

copy

Full Screen

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...

Full Screen

Full Screen

conftest.py

Source:conftest.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...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))...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { render } from 'react-dom'2import { storiesOf } from '@storybook/react'3import { withInfo } from '@storybook/addon-info'4import { withKnobs, text } from '@storybook/addon-knobs'5import { withA11y } from '@storybook/addon-a11y'6import { withTests } from '@storybook/addon-jest'7import results from '../.jest-test-results.json'8import { withStorySource } from '@storybook/addon-storysource'9import { withViewport } from '@storybook/addon-viewport'10import { withConsole } from '@storybook/addon-console'11import { withPerformance } from 'storybook-addon-performance'12import { withPercy } from '@percy-io/percy-storybook'13import { withFixtures } from 'storybook-addon-fixtures'14import { withContexts } from '@storybook/addon-contexts/react'15import { contexts } from './contexts'16import { withRedux } from 'addon-redux'17import { withBackgrounds } from '@storybook/addon-backgrounds'18import { backgrounds } from './backgrounds'19import { withDesign } from 'storybook-addon-designs'20import { withPropsTable } from 'storybook-addon-react-docgen'21import { withFormik } from 'storybook-addon-formik'22import { withReduxForm } from 'storybook-addon-redux-form'23import { withEmotion } from 'storybook-addon-emotion'24import { withStyledComponents } from 'storybook-addon-styled-component-theme'25import { withTests as withTests2 } from '@storybook/addon-jest'26import results2 from '../.jest-test-results.json'27import { withCreevey } from 'creevey-addon'28import { withInfo as withInfo2 } from '@storybook/addon-info'29import { withTests as withTests3 } from '@storybook/addon-jest'30import results3 from '../.jest-test-results.json'31import { withTests as withTests4 } from '@storybook/addon-jest'32import results4 from '../.jest-test-results.json'33import { withTests as withTests5 } from '@storybook/addon-jest'34import results5 from '../.jest-test-results.json'35import { withTests as withTests6 } from '@storybook/addon-jest'36import results6 from '../.jest-test-results.json'37import { withTests as withTests7 } from '@storybook/addon-jest'38import results7 from '../.jest-test-results

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { StorybookRoot } from 'storybook-root';4import { withInfo } from '@storybook/addon-info';5import { withKnobs, text } from '@storybook/addon-knobs';6import { action } from '@storybook/addon-actions';7import { withScreenshot } from 'storycap';8import { withA11y } from '@storybook/addon-a11y';9import { withPerformance } from 'storybook-addon-performance';10import { withTests } from '@storybook/addon-jest';11import results from '../.jest-test-results.json';12import { withConsole } from '@storybook/addon-console';13import { withViewport } from '@storybook/addon-viewport';14import { MyComponent } from '../src';15storiesOf('MyComponent', module)16 .addDecorator(17 withInfo({18 styles: {19 infoBody: {20 },21 },22 })23 .addDecorator(withKnobs)24 .addDecorator(withA11y)25 .addDecorator(withPerformance)26 .addDecorator(withTests({ results }))27 .addDecorator((storyFn, context) => withConsole()(storyFn)(context))28 .addDecorator(withViewport())29 .addDecorator(withScreenshot())30 .add('default', () => (31 text={text('text', 'hello storybook')}32 onClick={action('clicked')}33 ));34const path = require('path');35const root = path.join(__dirname, '../');36module.exports = ({ config }) => {37 config.module.rules.push({38 {39 options: {40 {41 targets: {42 },43 },44 },45 },46 });47 config.module.rules.push({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { fixture } from 'storybook-root';2const { fixture } = require('storybook-root');3const { fixture } = require('storybook-root');4import { fixture } from 'storybook-root';5const { fixture } = require('storybook-root');6const { fixture } = require('storybook-root');7import { fixture } from 'storybook-root';8const { fixture } = require('storybook-root');9const { fixture } = require('storybook-root');10import { fixture } from 'storybook-root';11const { fixture } = require('storybook-root');12const { fixture } = require('storybook-root');13import { fixture } from 'storybook-root';14const { fixture } = require('storybook-root');15const { fixture } = require('storybook-root');16import { fixture } from 'storybook-root';17const { fixture } = require('storybook-root');18const { fixture } = require('storybook-root');19import { fixture } from 'storybook-root';20const { fixture } = require('storybook-root');21const { fixture } = require('storybook-root');22import { fixture } from 'storybook-root';23const { fixture

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useFixture } from 'storybook-root';2import { render } from '@testing-library/react';3import { MyComponent } from './MyComponent';4test('MyComponent', () => {5 const fixture = useFixture('MyComponent');6 const { getByText } = render(<MyComponent {...fixture} />);7 expect(getByText(fixture.text)).toBeInTheDocument();8});9import { fixture } from 'storybook-root';10import { MyComponent } from './MyComponent';11export default {12};13export const Default = fixture({14});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { render } from "@testing-library/react";2import { withTestRouter } from "storybook-addon-test-router";3import { withTestLocation } from "storybook-addon-test-location";4import { withTestProvider } from "storybook-addon-test-provider";5import { withTestTheme } from "storybook-addon-test-theme";6import { withTestIntl } from "storybook-addon-test-intl";7import { withTestStore } from "storybook-addon-test-store";8import { stories } from "./App.stories";9const renderWithProviders = (storyFn) => {10 const Story = withTestRouter(withTestLocation(storyFn));11 const Story = withTestProvider(Story);12 const Story = withTestTheme(Story);13 const Story = withTestIntl(Story);14 const Story = withTestStore(Story);15 return render(Story);16};17describe("App", () => {18 Object.entries(stories).forEach(([name, story]) => {19 it(`should render ${name}`, () => {20 const { container } = renderWithProviders(story);21 expect(container.firstChild).toMatchSnapshot();22 });23 });24});25import React from "react";26import { storiesOf } from "@storybook/react";27import { withTestRouter } from "storybook-addon-test-router";28import { withTestLocation } from "storybook-addon-test-location";29import { withTestProvider } from "storybook-addon-test-provider";30import { withTestTheme } from "storybook-addon-test-theme";31import { withTestIntl } from "storybook-addon-test-intl";32import { withTestStore } from "storybook-addon-test-store";33import { App } from "./App";34import { Button } from "./Button";35export const fixture = (storyFn) => {36 const Story = withTestRouter(withTestLocation(storyFn));37 const Story = withTestProvider(Story);38 const Story = withTestTheme(Story);39 const Story = withTestIntl(Story);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withStorybookRoot } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('Test', module)4 .add('test', () => {5 return withStorybookRoot({6 },7 fixture: (component, store) => {8 return component;9 }10 });11 });12import { withStorybookRoot } from 'storybook-root';13import { storiesOf } from '@storybook/react';14storiesOf('Test', module)15 .add('test', () => {16 return withStorybookRoot({17 },18 fixture: (component, store) => {19 return component;20 }21 });22 });23import { withStorybookRoot } from 'storybook-root';24import { storiesOf } from '@storybook/react';25storiesOf('Test', module)26 .add('test', () => {27 return withStorybookRoot({28 },29 fixture: (component, store) => {30 return component;31 }32 });33 });34import { withStorybookRoot } from 'storybook-root';35import { storiesOf } from '@storybook/react';36storiesOf('Test', module)37 .add('test', () => {38 return withStorybookRoot({39 },40 fixture: (component, store) => {41 return component;42 }43 });44 });45import { withStorybookRoot } from 'storybook-root';46import { storiesOf } from '@storybook/react';47storiesOf('Test', module)48 .add('test', () => {49 return withStorybookRoot({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { render } from "@testing-library/react";2import React from "react";3import { Card } from "../Card";4import { card } from "../Card.stories";5it("renders card", () => {6 const { container } = render(card());7 expect(container).toMatchSnapshot();8});9import React from "react";10import { Card } from "./Card";11export default {12};13export const card = () => <Card>Content</Card>;14card.story = {15};16import React from "react";17export const Card = (props) => <div className="card">{props.children}</div>;18export default Card;19import PropTypes from "prop-types";20export const customPropType = PropTypes.shape({21});22import React from "react";23import PropTypes from "prop-types";24import { customPropType } from "../prop-types";25export const CustomComponent = ({ customProp }) => {26 return <div>{customProp.foo}</div>;27};28CustomComponent.propTypes = {29};30import React from "react";31import { CustomComponent } from "./CustomComponent";32export default {33};34export const customComponent = () => <CustomComponent />;35customComponent.story = {36};37import { addDecorator, addParameters } from "@storybook/react";38import { withA11y } from "@storybook/addon-a11y";39import { withInfo } from "@storybook/addon-info";40import { withTests } from "@storybook/addon-jest";41import results from "../.jest-test-results.json";42import "./storybook.css";43addDecorator(withA11y);44addDecorator(withInfo);45addParameters({46 info: {47 },48});49addDecorator(50 withTests({51 })52);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful