Best Python code snippet using assertpy_python
__init__.py
Source:__init__.py
1import six2import unittest3import warnings4from scrapy.settings import Settings, SettingsAttribute, CrawlerSettings5from tests import mock6from . import default_settings7class SettingsAttributeTest(unittest.TestCase):8 def setUp(self):9 self.attribute = SettingsAttribute('value', 10)10 def test_set_greater_priority(self):11 self.attribute.set('value2', 20)12 self.assertEqual(self.attribute.value, 'value2')13 self.assertEqual(self.attribute.priority, 20)14 def test_set_equal_priority(self):15 self.attribute.set('value2', 10)16 self.assertEqual(self.attribute.value, 'value2')17 self.assertEqual(self.attribute.priority, 10)18 def test_set_less_priority(self):19 self.attribute.set('value2', 0)20 self.assertEqual(self.attribute.value, 'value')21 self.assertEqual(self.attribute.priority, 10)22class SettingsTest(unittest.TestCase):23 if six.PY3:24 assertItemsEqual = unittest.TestCase.assertCountEqual25 def setUp(self):26 self.settings = Settings()27 @mock.patch.dict('scrapy.settings.SETTINGS_PRIORITIES', {'default': 10})28 @mock.patch('scrapy.settings.default_settings', default_settings)29 def test_initial_defaults(self):30 settings = Settings()31 self.assertEqual(len(settings.attributes), 1)32 self.assertIn('TEST_DEFAULT', settings.attributes)33 attr = settings.attributes['TEST_DEFAULT']34 self.assertIsInstance(attr, SettingsAttribute)35 self.assertEqual(attr.value, 'defvalue')36 self.assertEqual(attr.priority, 10)37 @mock.patch.dict('scrapy.settings.SETTINGS_PRIORITIES', {})38 @mock.patch('scrapy.settings.default_settings', {})39 def test_initial_values(self):40 settings = Settings({'TEST_OPTION': 'value'}, 10)41 self.assertEqual(len(settings.attributes), 1)42 self.assertIn('TEST_OPTION', settings.attributes)43 attr = settings.attributes['TEST_OPTION']44 self.assertIsInstance(attr, SettingsAttribute)45 self.assertEqual(attr.value, 'value')46 self.assertEqual(attr.priority, 10)47 def test_set_new_attribute(self):48 self.settings.attributes = {}49 self.settings.set('TEST_OPTION', 'value', 0)50 self.assertIn('TEST_OPTION', self.settings.attributes)51 attr = self.settings.attributes['TEST_OPTION']52 self.assertIsInstance(attr, SettingsAttribute)53 self.assertEqual(attr.value, 'value')54 self.assertEqual(attr.priority, 0)55 def test_set_instance_identity_on_update(self):56 attr = SettingsAttribute('value', 0)57 self.settings.attributes = {'TEST_OPTION': attr}58 self.settings.set('TEST_OPTION', 'othervalue', 10)59 self.assertIn('TEST_OPTION', self.settings.attributes)60 self.assertIs(attr, self.settings.attributes['TEST_OPTION'])61 def test_set_calls_settings_attributes_methods_on_update(self):62 with mock.patch.object(SettingsAttribute, '__setattr__') as mock_setattr, \63 mock.patch.object(SettingsAttribute, 'set') as mock_set:64 attr = SettingsAttribute('value', 10)65 self.settings.attributes = {'TEST_OPTION': attr}66 mock_set.reset_mock()67 mock_setattr.reset_mock()68 for priority in (0, 10, 20):69 self.settings.set('TEST_OPTION', 'othervalue', priority)70 mock_set.assert_called_once_with('othervalue', priority)71 self.assertFalse(mock_setattr.called)72 mock_set.reset_mock()73 mock_setattr.reset_mock()74 def test_setdict_alias(self):75 with mock.patch.object(self.settings, 'set') as mock_set:76 self.settings.setdict({'TEST_1': 'value1', 'TEST_2': 'value2'}, 10)77 self.assertEqual(mock_set.call_count, 2)78 calls = [mock.call('TEST_1', 'value1', 10),79 mock.call('TEST_2', 'value2', 10)]80 mock_set.assert_has_calls(calls, any_order=True)81 def test_setmodule_only_load_uppercase_vars(self):82 class ModuleMock():83 UPPERCASE_VAR = 'value'84 MIXEDcase_VAR = 'othervalue'85 lowercase_var = 'anothervalue'86 self.settings.attributes = {}87 self.settings.setmodule(ModuleMock(), 10)88 self.assertIn('UPPERCASE_VAR', self.settings.attributes)89 self.assertNotIn('MIXEDcase_VAR', self.settings.attributes)90 self.assertNotIn('lowercase_var', self.settings.attributes)91 self.assertEqual(len(self.settings.attributes), 1)92 def test_setmodule_alias(self):93 with mock.patch.object(self.settings, 'set') as mock_set:94 self.settings.setmodule(default_settings, 10)95 mock_set.assert_called_with('TEST_DEFAULT', 'defvalue', 10)96 def test_setmodule_by_path(self):97 self.settings.attributes = {}98 self.settings.setmodule(default_settings, 10)99 ctrl_attributes = self.settings.attributes.copy()100 self.settings.attributes = {}101 self.settings.setmodule(102 'tests.test_settings.default_settings', 10)103 self.assertItemsEqual(six.iterkeys(self.settings.attributes),104 six.iterkeys(ctrl_attributes))105 for attr, ctrl_attr in zip(six.itervalues(self.settings.attributes),106 six.itervalues(ctrl_attributes)):107 self.assertEqual(attr.value, ctrl_attr.value)108 self.assertEqual(attr.priority, ctrl_attr.priority)109 def test_get(self):110 test_configuration = {111 'TEST_ENABLED1': '1',112 'TEST_ENABLED2': True,113 'TEST_ENABLED3': 1,114 'TEST_DISABLED1': '0',115 'TEST_DISABLED2': False,116 'TEST_DISABLED3': 0,117 'TEST_INT1': 123,118 'TEST_INT2': '123',119 'TEST_FLOAT1': 123.45,120 'TEST_FLOAT2': '123.45',121 'TEST_LIST1': ['one', 'two'],122 'TEST_LIST2': 'one,two',123 'TEST_STR': 'value',124 'TEST_DICT1': {'key1': 'val1', 'ke2': 3},125 'TEST_DICT2': '{"key1": "val1", "ke2": 3}',126 }127 settings = self.settings128 settings.attributes = {key: SettingsAttribute(value, 0) for key, value129 in six.iteritems(test_configuration)}130 self.assertTrue(settings.getbool('TEST_ENABLED1'))131 self.assertTrue(settings.getbool('TEST_ENABLED2'))132 self.assertTrue(settings.getbool('TEST_ENABLED3'))133 self.assertFalse(settings.getbool('TEST_ENABLEDx'))134 self.assertTrue(settings.getbool('TEST_ENABLEDx', True))135 self.assertFalse(settings.getbool('TEST_DISABLED1'))136 self.assertFalse(settings.getbool('TEST_DISABLED2'))137 self.assertFalse(settings.getbool('TEST_DISABLED3'))138 self.assertEqual(settings.getint('TEST_INT1'), 123)139 self.assertEqual(settings.getint('TEST_INT2'), 123)140 self.assertEqual(settings.getint('TEST_INTx'), 0)141 self.assertEqual(settings.getint('TEST_INTx', 45), 45)142 self.assertEqual(settings.getfloat('TEST_FLOAT1'), 123.45)143 self.assertEqual(settings.getfloat('TEST_FLOAT2'), 123.45)144 self.assertEqual(settings.getfloat('TEST_FLOATx'), 0.0)145 self.assertEqual(settings.getfloat('TEST_FLOATx', 55.0), 55.0)146 self.assertEqual(settings.getlist('TEST_LIST1'), ['one', 'two'])147 self.assertEqual(settings.getlist('TEST_LIST2'), ['one', 'two'])148 self.assertEqual(settings.getlist('TEST_LISTx'), [])149 self.assertEqual(settings.getlist('TEST_LISTx', ['default']), ['default'])150 self.assertEqual(settings['TEST_STR'], 'value')151 self.assertEqual(settings.get('TEST_STR'), 'value')152 self.assertEqual(settings['TEST_STRx'], None)153 self.assertEqual(settings.get('TEST_STRx'), None)154 self.assertEqual(settings.get('TEST_STRx', 'default'), 'default')155 self.assertEqual(settings.getdict('TEST_DICT1'), {'key1': 'val1', 'ke2': 3})156 self.assertEqual(settings.getdict('TEST_DICT2'), {'key1': 'val1', 'ke2': 3})157 self.assertEqual(settings.getdict('TEST_DICT3'), {})158 self.assertEqual(settings.getdict('TEST_DICT3', {'key1': 5}), {'key1': 5})159 self.assertRaises(ValueError, settings.getdict, 'TEST_LIST1')160 def test_copy(self):161 values = {162 'TEST_BOOL': True,163 'TEST_LIST': ['one', 'two'],164 'TEST_LIST_OF_LISTS': [['first_one', 'first_two'],165 ['second_one', 'second_two']]166 }167 self.settings.setdict(values)168 copy = self.settings.copy()169 self.settings.set('TEST_BOOL', False)170 self.assertTrue(copy.get('TEST_BOOL'))171 test_list = self.settings.get('TEST_LIST')172 test_list.append('three')173 self.assertListEqual(copy.get('TEST_LIST'), ['one', 'two'])174 test_list_of_lists = self.settings.get('TEST_LIST_OF_LISTS')175 test_list_of_lists[0].append('first_three')176 self.assertListEqual(copy.get('TEST_LIST_OF_LISTS')[0],177 ['first_one', 'first_two'])178 def test_freeze(self):179 self.settings.freeze()180 with self.assertRaises(TypeError) as cm:181 self.settings.set('TEST_BOOL', False)182 self.assertEqual(str(cm.exception),183 "Trying to modify an immutable Settings object")184 def test_frozencopy(self):185 frozencopy = self.settings.frozencopy()186 self.assertTrue(frozencopy.frozen)187 self.assertIsNot(frozencopy, self.settings)188 def test_deprecated_attribute_overrides(self):189 self.settings.set('BAR', 'fuz', priority='cmdline')190 with warnings.catch_warnings(record=True) as w:191 self.settings.overrides['BAR'] = 'foo'192 self.assertIn("Settings.overrides", str(w[0].message))193 self.assertEqual(self.settings.get('BAR'), 'foo')194 self.assertEqual(self.settings.overrides.get('BAR'), 'foo')195 self.assertIn('BAR', self.settings.overrides)196 self.settings.overrides.update(BAR='bus')197 self.assertEqual(self.settings.get('BAR'), 'bus')198 self.assertEqual(self.settings.overrides.get('BAR'), 'bus')199 self.settings.overrides.setdefault('BAR', 'fez')200 self.assertEqual(self.settings.get('BAR'), 'bus')201 self.settings.overrides.setdefault('FOO', 'fez')202 self.assertEqual(self.settings.get('FOO'), 'fez')203 self.assertEqual(self.settings.overrides.get('FOO'), 'fez')204 def test_deprecated_attribute_defaults(self):205 self.settings.set('BAR', 'fuz', priority='default')206 with warnings.catch_warnings(record=True) as w:207 self.settings.defaults['BAR'] = 'foo'208 self.assertIn("Settings.defaults", str(w[0].message))209 self.assertEqual(self.settings.get('BAR'), 'foo')210 self.assertEqual(self.settings.defaults.get('BAR'), 'foo')211 self.assertIn('BAR', self.settings.defaults)212class CrawlerSettingsTest(unittest.TestCase):213 def test_deprecated_crawlersettings(self):214 def _get_settings(settings_dict=None):215 settings_module = type('SettingsModuleMock', (object,), settings_dict or {})216 return CrawlerSettings(settings_module)217 with warnings.catch_warnings(record=True) as w:218 settings = _get_settings()219 self.assertIn("CrawlerSettings is deprecated", str(w[0].message))220 # test_global_defaults221 self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 180)222 # test_defaults223 settings.defaults['DOWNLOAD_TIMEOUT'] = '99'224 self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 99)225 # test_settings_module226 settings = _get_settings({'DOWNLOAD_TIMEOUT': '3'})227 self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 3)228 # test_overrides229 settings = _get_settings({'DOWNLOAD_TIMEOUT': '3'})230 settings.overrides['DOWNLOAD_TIMEOUT'] = '15'231 self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 15)232if __name__ == "__main__":...
test_search.py
Source:test_search.py
1# -*- coding: utf-8 -*-2# to run, from /panelcode-master:3# python -m tests.test_search4from .context import panelcode5from panelcode import *6import unittest7class SearchTestSuite(unittest.TestCase):8 """Search test cases."""9 10 def test_list_to_string(self):11 expected = '1\n2\n3'12 tests = []13 tests.append( ['1','2','3'] ) ## strings14 tests.append( ['1 ',' 2',' 3 '] ) ## spaced15 tests.append( [1,2,3] ) ## ints16 tests.append( [1,'2',' 3 '] ) ## mixed17 for i in tests:18 self.assertEqual( utils.list_to_string(i), expected )19 ## test 'join' kwarg20 self.assertEqual( utils.list_to_string(['1','2','3'], join=';'), '1;2;3' )21 self.assertEqual( utils.list_to_string(['1 ',' 2',' 3 '], join=' '), '1 2 3' )22 self.assertEqual( utils.list_to_string([1,2,3], join='\n'), '1\n2\n3' )23 self.assertEqual( utils.list_to_string([1,'2',' 3 '], join=','), '1,2,3' )24 def test_list_counter(self): 25 """ """26 ## https://docs.python.org/2.7/library/collections.html#collections.Counter27 test_list_ = ['1','2','3','4','5','6']28 c = search.list_counter(test_list_)29 ## inspect counters30 # self.counter_stats(c)31 def test_list_of_lists_counter(self): 32 """ """33 test_list_of_lists = [['1','2','3'],['4','5','6']]34 c = search.list_of_lists_counter(test_list_of_lists)35 ## inspect counters36 # self.counter_stats(c)37 def test_list_contains(self):38 """ """39 test_list_ = ['1','2','3','4','5','6']40 self.assertTrue (search.list_contains(test_list_, '1'))41 self.assertFalse(search.list_contains(test_list_, '7'))42 def test_list_of_lists_contains(self):43 """ """44 test_list_of_lists = [['1','2','3'],['4','5','6']]45 self.assertTrue (search.list_of_lists_contains(test_list_of_lists, '1'))46 self.assertFalse(search.list_of_lists_contains(test_list_of_lists, '7'))47 def counter_stats(self, c):48 """test function for inspecting counters"""49 print c50 print ' most common:'51 print c.most_common(3)52 print ' least common:'53 print c.most_common()[:-4:-1] # n least common elements (:-n-1:-1)54 print ' total of counts:'55 print sum(c.values()) # total of all counts56 print ' unique elements:'57 print list(c) # list unique elements58 print ' set:'59 print set(c) # convert to a set60 print ' dict:'61 print dict(c) # convert to a regular dictionary62 print ' list of pairs:'63 print c.items() # convert to a list of (elem, cnt) pairs64 c += Counter(); print c # remove zero and negative counts65 c.clear(); print c # reset all counts66 67if __name__ == '__main__':...
stats.py
Source:stats.py
1# Let's use train.label.txt2train_labeltxt = open('./data/train.label.txt', "r")3train_label = train_labeltxt.read()4train_labeltxt.close()5examples_labels_list = train_label.splitlines()6# list containing lists with the label of each input train example7train_list_of_lists = [example.split() for example in examples_labels_list] 8# Let's use test.label.txt9test_labeltxt = open('./data/test.label.txt', "r")10test_label = test_labeltxt.read()11test_labeltxt.close()12test_examples_labels_list = test_label.splitlines()13# list containing lists with the label of each input test example14test_list_of_lists = [example.split() for example in test_examples_labels_list]15def label_parts(label): # function to get the BIO tag and constituent tags separately16 17 label_BIO = label[0]18 label_POS = label[2:]19 return label_BIO, label_POS20def contraints_counters(lista): # counting statistics for constraints for one input sequence21 22 counter_c1 = 0 # counter for constraint I follows O23 counter_c2 = 0 # counter for constraint I of a class follows B of a different class24 counter_c3 = 0 # counter for B-VP25 b_vp = False # Flag for the presence of B-VP in the input sentence26 27 for i in range(len(lista)-1):28 29 if label_parts(lista[i])[0]=='O' and label_parts(lista[i+1])[0]=='I':30 #print('EJE')31 counter_c1+=132 if label_parts(lista[i])[0]=='B' and label_parts(lista[i+1])[0]=='I' and label_parts(lista[i])[1]!=label_parts(lista[i+1])[1]:33 #print('UPA')34 counter_c2+=135 if label_parts(lista[i])[0]=='B' and label_parts(lista[i])[1]=='VP':36 #print('AJA')37 counter_c3+=138 39 if label_parts(lista[len(lista)-1])[0]=='B' and label_parts(lista[len(lista)-1])[1]=='VP':40 counter_c3+=141 if counter_c3!=0:42 b_vp = True43 return counter_c1, counter_c2, counter_c3, b_vp44# TRAIN SET SIZE 893645#print(len(train_list_of_lists))46# TEST SET SIZE 201247#print(len(test_list_of_lists))48def constraints_stats(list_of_lists): # stats of constraints for whole data49 50 total_c1=051 total_c2=052 total_c3=053 total_b_vp_not=054 55 for input_sent in list_of_lists:56 con_1, con_2, con_3, b_vp_is = contraints_counters(input_sent)57 total_c1+=con_158 total_c2+=con_259 total_c3+=con_360 if b_vp_is==False:61 total_b_vp_not+=162 63 return total_c1, total_c2, total_c3, total_b_vp_not64print(constraints_stats(train_list_of_lists))65# Number of input train sentences that do not contain B-VP tag: 29366print(constraints_stats(test_list_of_lists))...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!