How to use Store method in istanbul

Best JavaScript code snippet using istanbul

sentinel.py

Source:sentinel.py Github

copy

Full Screen

...438 run = tools.printDetectScan(db_store, id_)439 sys.exit(0)440 if sys.argv[1] == 'detect-scan':441 ip = sys.argv[2]442 scan = tools.nmapDetectScanStore(ip, db_store)443 print(str(scan))444 sys.exit(0)445 if sys.argv[1] == 'del-detect':446 id_ = sys.argv[2]447 del_ = store.deleteDetect(id_, db_store)448 print(del_)449 sys.exit(0)450 if sys.argv[1] == 'clear-detects':451 clear = store.clearAllDetects(db_store)452 print(clear)453 sys.exit(0)454 if sys.argv[1] == 'port-scan':455 ipnet = None456 level = 1...

Full Screen

Full Screen

test_object_store.py

Source:test_object_store.py Github

copy

Full Screen

...163 self.store.close()164class MemoryObjectStoreTests(ObjectStoreTests, TestCase):165 def setUp(self):166 TestCase.setUp(self)167 self.store = MemoryObjectStore()168 def test_add_pack(self):169 o = MemoryObjectStore()170 f, commit, abort = o.add_pack()171 try:172 b = make_object(Blob, data=b"more yummy data")173 write_pack_objects(f, [(b, None)])174 except:175 abort()176 raise177 else:178 commit()179 def test_add_pack_emtpy(self):180 o = MemoryObjectStore()181 f, commit, abort = o.add_pack()182 commit()183 def test_add_thin_pack(self):184 o = MemoryObjectStore()185 blob = make_object(Blob, data=b'yummy data')186 o.add_object(blob)187 f = BytesIO()188 entries = build_pack(f, [189 (REF_DELTA, (blob.id, b'more yummy data')),190 ], store=o)191 o.add_thin_pack(f.read, None)192 packed_blob_sha = sha_to_hex(entries[0][3])193 self.assertEqual((Blob.type_num, b'more yummy data'),194 o.get_raw(packed_blob_sha))195 def test_add_thin_pack_empty(self):196 o = MemoryObjectStore()197 f = BytesIO()198 entries = build_pack(f, [], store=o)199 self.assertEqual([], entries)200 o.add_thin_pack(f.read, None)201class PackBasedObjectStoreTests(ObjectStoreTests):202 def tearDown(self):203 for pack in self.store.packs:204 pack.close()205 def test_empty_packs(self):206 self.assertEqual([], list(self.store.packs))207 def test_pack_loose_objects(self):208 b1 = make_object(Blob, data=b"yummy data")209 self.store.add_object(b1)210 b2 = make_object(Blob, data=b"more yummy data")211 self.store.add_object(b2)212 self.assertEqual([], list(self.store.packs))213 self.assertEqual(2, self.store.pack_loose_objects())214 self.assertNotEqual([], list(self.store.packs))215 self.assertEqual(0, self.store.pack_loose_objects())216class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):217 def setUp(self):218 TestCase.setUp(self)219 self.store_dir = tempfile.mkdtemp()220 self.addCleanup(shutil.rmtree, self.store_dir)221 self.store = DiskObjectStore.init(self.store_dir)222 def tearDown(self):223 TestCase.tearDown(self)224 PackBasedObjectStoreTests.tearDown(self)225 def test_alternates(self):226 alternate_dir = tempfile.mkdtemp()227 self.addCleanup(shutil.rmtree, alternate_dir)228 alternate_store = DiskObjectStore(alternate_dir)229 b2 = make_object(Blob, data=b"yummy data")230 alternate_store.add_object(b2)231 store = DiskObjectStore(self.store_dir)232 self.assertRaises(KeyError, store.__getitem__, b2.id)233 store.add_alternate_path(alternate_dir)234 self.assertIn(b2.id, store)235 self.assertEqual(b2, store[b2.id])236 def test_add_alternate_path(self):237 store = DiskObjectStore(self.store_dir)238 self.assertEqual([], list(store._read_alternate_paths()))239 store.add_alternate_path("/foo/path")240 self.assertEqual(["/foo/path"], list(store._read_alternate_paths()))241 store.add_alternate_path("/bar/path")242 self.assertEqual(243 ["/foo/path", "/bar/path"],244 list(store._read_alternate_paths()))245 def test_rel_alternative_path(self):246 alternate_dir = tempfile.mkdtemp()247 self.addCleanup(shutil.rmtree, alternate_dir)248 alternate_store = DiskObjectStore(alternate_dir)249 b2 = make_object(Blob, data=b"yummy data")250 alternate_store.add_object(b2)251 store = DiskObjectStore(self.store_dir)252 self.assertRaises(KeyError, store.__getitem__, b2.id)253 store.add_alternate_path(os.path.relpath(alternate_dir, self.store_dir))254 self.assertEqual(list(alternate_store), list(store.alternates[0]))255 self.assertIn(b2.id, store)256 self.assertEqual(b2, store[b2.id])257 def test_pack_dir(self):258 o = DiskObjectStore(self.store_dir)259 self.assertEqual(os.path.join(self.store_dir, "pack"), o.pack_dir)260 def test_add_pack(self):261 o = DiskObjectStore(self.store_dir)262 f, commit, abort = o.add_pack()263 try:264 b = make_object(Blob, data=b"more yummy data")265 write_pack_objects(f, [(b, None)])266 except:267 abort()268 raise269 else:270 commit()271 def test_add_thin_pack(self):272 o = DiskObjectStore(self.store_dir)273 try:274 blob = make_object(Blob, data=b'yummy data')275 o.add_object(blob)276 f = BytesIO()277 entries = build_pack(f, [278 (REF_DELTA, (blob.id, b'more yummy data')),279 ], store=o)280 with o.add_thin_pack(f.read, None) as pack:281 packed_blob_sha = sha_to_hex(entries[0][3])282 pack.check_length_and_checksum()283 self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack))284 self.assertTrue(o.contains_packed(packed_blob_sha))285 self.assertTrue(o.contains_packed(blob.id))286 self.assertEqual((Blob.type_num, b'more yummy data'),287 o.get_raw(packed_blob_sha))288 finally:289 o.close()290 def test_add_thin_pack_empty(self):291 with closing(DiskObjectStore(self.store_dir)) as o:292 f = BytesIO()293 entries = build_pack(f, [], store=o)294 self.assertEqual([], entries)295 o.add_thin_pack(f.read, None)296class TreeLookupPathTests(TestCase):297 def setUp(self):298 TestCase.setUp(self)299 self.store = MemoryObjectStore()300 blob_a = make_object(Blob, data=b'a')301 blob_b = make_object(Blob, data=b'b')302 blob_c = make_object(Blob, data=b'c')303 for blob in [blob_a, blob_b, blob_c]:304 self.store.add_object(blob)305 blobs = [306 (b'a', blob_a.id, 0o100644),307 (b'ad/b', blob_b.id, 0o100644),308 (b'ad/bd/c', blob_c.id, 0o100755),309 (b'ad/c', blob_c.id, 0o100644),310 (b'c', blob_c.id, 0o100644),311 ]312 self.tree_id = commit_tree(self.store, blobs)313 def get_object(self, sha):...

Full Screen

Full Screen

gitegridy.py

Source:gitegridy.py Github

copy

Full Screen

1#!/usr/bin/env python32import os3from subprocess import Popen, PIPE4import sys5def gitStoreLink(git_store, List, verbose=False):6 if not os.path.isdir(git_store):7 if verbose: print('mkdir ' + str(git_store))8 os.mkdir(git_store, 0o755)9 for f in List:10 gfile = git_store + f11 if not os.path.isdir(os.path.dirname(gfile)):12 if verbose: print('mkdir ' + str(os.path.dirname(gfile)))13 os.mkdir(os.path.dirname(gfile), 0o755)14 if not os.path.isfile(gfile):15 if verbose: print('link ' + str(gfile))16 os.link(f, gfile)17 return True18def gitStoreInit(git_store, verbose=False):19 if not os.path.isdir(git_store):20 if verbose: print('mkdir ' + str(git_store))21 os.mkdir(git_store, 0o755)22 if not os.path.isdir(git_store + '/.git'):23 if verbose: print('git init ' + str(git_store))24 cmd = 'git init ' + str(git_store)25 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)26 if verbose:27 for line in proc.stdout.readlines():28 print(line.decode('utf-8').strip('\n'))29 #os.chdir(git_store)30 return True31def gitStoreAdd(git_store, f, verbose=False):32 try:33 os.chdir(git_store)34 except FileNotFoundError as e:35 if verbose: print('FileNotFoundError: ' + str(e))36 return 'FileNotFoundError: ' + str(e)37 if not os.access(f, os.F_OK):38 if verbose: print('Not Found: ' + str(f))39 return 'Not Found: ' + str(f)40 elif not os.access(f, os.R_OK):41 if verbose: print('No Access: ' + str(f))42 return 'No Access: ' + str(f)43 cmd = 'git add ' + git_store + f44 if verbose: print('git add ' + git_store + f)45 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)46 stdout, stderr = proc.communicate()47 exit_code = proc.wait()48 if verbose:49 print(stdout.decode('utf-8'))50 print(stderr.decode('utf-8'))51 print(str(exit_code))52 return stdout, stderr, exit_code53def gitStoreDel(git_store, f, verbose=False):54 os.chdir(git_store)55 if verbose: print('git rm ' + git_store + f)56 cmd = 'git rm -f ' + git_store + f57 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)58 if verbose:59 for line in proc.stdout.readlines():60 print(line.decode('utf-8').strip('\n'))61 if os.path.exists(git_store + f):62 if verbose: print('remove ' + git_store + f)63 os.remove(git_store + f)64 git_commit = gitStoreCommit(git_store, f, verbose=True)65 return True66 67def gitStoreCommit(git_store, f, verbose=False):68 os.chdir(git_store)69 if verbose: print('git commit me ' + git_store + f)70 #import shlex71 #shlex.split(cmd)72 #cmd = 'git commit -m "sentinel" ' + git_store + f73 #proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)74 cmd = ['git', 'commit', '-m', '"sentinel ' + str(f) + '"', git_store + f ]75 proc = Popen(cmd, stdout=PIPE, stderr=PIPE)76 stdout, stderr = proc.communicate()77 exit_code = proc.wait()78 if verbose:79 print(stdout.decode('utf-8'))80 print(stderr.decode('utf-8'))81 print(str(exit_code))82 return stdout, stderr, exit_code83def gitStoreStatus(git_store, verbose=False):84 try:85 os.chdir(git_store)86 except FileNotFoundError as e:87 if verbose: print('FileNotFoundError: ' + str(e))88 return 'FileNotFoundError: ' + str(e)89 cmd = 'git status'90 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)91 stdout, stderr = proc.communicate()92 exit_code = proc.wait()93 if verbose:94 print(stdout.decode('utf-8'))95 print(stderr.decode('utf-8'))96 print(str(exit_code))97 return stdout, stderr, exit_code98def gitStoreLsFiles(git_store, verbose=False):99 try:100 os.chdir(git_store)101 except FileNotFoundError as e:102 if verbose: print('FileNotFoundError: ' + str(e))103 return 'FileNotFoundError: ' + str(e)104 cmd = 'git ls-files'105 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)106 stdout, stderr = proc.communicate()107 exit_code = proc.wait()108 if verbose:109 print(stdout.decode('utf-8'))110 print(stderr.decode('utf-8'))111 print(str(exit_code))112 return stdout, stderr, exit_code113def gitStoreLog(git_store, verbose=False):114 try:115 os.chdir(git_store)116 except FileNotFoundError as e:117 if verbose: print('FileNotFoundError: ' + str(e))118 return 'FileNotFoundError: ' + str(e)119 cmd = 'git log'120 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)121 if verbose:122 for line in proc.stdout.readlines():123 print(line.decode('utf-8').strip('\n'))124 return proc.stdout.readlines()125def gitStoreClearHistory(git_store, verbose=False):126 os.chdir(git_store)127 cmd = 'git checkout --orphan temp_branch'128 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)129 if verbose:130 for line in proc.stdout.readlines():131 print(line.decode('utf-8').strip('\n'))132 cmd = 'git add -A'133 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)134 if verbose:135 for line in proc.stdout.readlines():136 print(line.decode('utf-8').strip('\n'))137 cmd = ['git','commit','-am "sentinel re-commit"']138 proc = Popen(cmd, stdout=PIPE, stderr=PIPE)139 if verbose:140 for line in proc.stdout.readlines():141 print(line.decode('utf-8').strip('\n'))142 cmd = 'git branch -D master'143 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)144 if verbose:145 for line in proc.stdout.readlines():146 print(line.decode('utf-8').strip('\n'))147 cmd = 'git branch -m master'148 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)149 if verbose:150 for line in proc.stdout.readlines():151 print(line.decode('utf-8').strip('\n'))152 #cmd = 'git push -f origin master'153 #proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)154 #if verbose:155 # for line in proc.stdout.readlines():156 # print(line.decode('utf-8').strip('\n'))157 return True158#import mimetypes159#mime = mimetypes.guess_type(file)160def fileType(_file):161 try:162 with open(_file, 'r', encoding='utf-8') as f:163 f.read(4)164 return 'text'165 except UnicodeDecodeError:166 return 'binary'167def gitStoreDiff(git_store, f=None, verbose=False):168 try:169 os.chdir(git_store)170 except FileNotFoundError as e:171 if verbose: print('FileNotFoundError: ' + str(e))172 return 'FileNotFoundError: ' + str(e)173 if f is None:174 f = ''175 cmd = 'git diff ' + f176 proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)177 stdout, stderr = proc.communicate()178 exit_code = proc.wait()179 if verbose:180 print(stdout.decode('utf-8'))181 print(stderr.decode('utf-8'))182 print(str(exit_code))183 return stdout, stderr, exit_code184if __name__ == '__main__':185 git_store = '/opt/sentinel/db/git/dir2'186 L = [ '/etc/hosts', '/etc/ssh/sshd_config' ]187 git_init = gitStoreInit(git_store)188 git_link = gitStoreLink(git_store, L)189 #for f in L:190 # git_add = gitStoreAdd(git_store, f)191 # git_commit = gitStoreCommit(git_store, f)192 if sys.argv[1:]:193 if sys.argv[1] == 'git-status':194 git_status = gitStoreStatus(git_store, verbose=True)195 if sys.argv[1] == 'git-files':196 git_files = gitStoreLsFiles(git_store, verbose=True)197 if sys.argv[1] == 'git-log':198 git_log = gitStoreLog(git_store, verbose=True)199 if sys.argv[1] == 'git-add':200 _file = sys.argv[2]201 if not os.access(_file, os.F_OK):202 print('Not Found: ' + str(_file))203 sys.exit(1)204 elif not os.access(_file, os.R_OK):205 print('No Access: ' + str(_file))206 sys.exit(1)207 git_link = gitStoreLink(git_store, [_file], verbose=True)208 git_add = gitStoreAdd(git_store, _file, verbose=True)209 git_commit = gitStoreCommit(git_store, _file, verbose=True)210 if sys.argv[1] == 'git-del':211 _file = sys.argv[2]212 git_del = gitStoreDel(git_store, _file, verbose=True)213 if sys.argv[1] == 'git-commit':214 _file = sys.argv[2]215 if not os.access(_file, os.F_OK):216 print('Not Found: ' + str(_file))217 sys.exit(1)218 elif not os.access(_file, os.R_OK):219 print('No Access: ' + str(_file))220 sys.exit(1)221 git_commit = gitStoreCommit(git_store, _file, verbose=True)222 if sys.argv[1] == 'git-clear-history':223 git_clear_hist = gitStoreClearHistory(git_store, verbose=True)224 if sys.argv[1] == 'git-diff':225 try: _file = sys.argv[2]226 except IndexError: _file = None227 git_diff = gitStoreDiff(git_store, _file, verbose=True)228 if sys.argv[1] == 'git-init':229 git_init = gitStoreInit(git_store)230 if sys.argv[1] == 'file-type':231 _file = sys.argv[2]232 file_type = fileType(_file)233 print(file_type)...

Full Screen

Full Screen

test_modulestore_settings.py

Source:test_modulestore_settings.py Github

copy

Full Screen

1"""2Tests for testing the modulestore settings migration code.3"""4import copy5import ddt6from tempfile import mkdtemp7from unittest import TestCase8from xmodule.modulestore.modulestore_settings import (9 convert_module_store_setting_if_needed,10 update_module_store_settings,11 get_mixed_stores,12)13@ddt.ddt14class ModuleStoreSettingsMigration(TestCase):15 """16 Tests for the migration code for the module store settings17 """18 OLD_CONFIG = {19 "default": {20 "ENGINE": "xmodule.modulestore.xml.XMLModuleStore",21 "OPTIONS": {22 "data_dir": "directory",23 "default_class": "xmodule.hidden_module.HiddenDescriptor",24 },25 "DOC_STORE_CONFIG": {},26 }27 }28 OLD_CONFIG_WITH_DIRECT_MONGO = {29 "default": {30 "ENGINE": "xmodule.modulestore.mongo.MongoModuleStore",31 "OPTIONS": {32 "collection": "modulestore",33 "db": "edxapp",34 "default_class": "xmodule.hidden_module.HiddenDescriptor",35 "fs_root": mkdtemp(),36 "host": "localhost",37 "password": "password",38 "port": 27017,39 "render_template": "edxmako.shortcuts.render_to_string",40 "user": "edxapp"41 },42 "DOC_STORE_CONFIG": {},43 }44 }45 OLD_MIXED_CONFIG_WITH_DICT = {46 "default": {47 "ENGINE": "xmodule.modulestore.mixed.MixedModuleStore",48 "OPTIONS": {49 "mappings": {},50 "stores": {51 "an_old_mongo_store": {52 "DOC_STORE_CONFIG": {},53 "ENGINE": "xmodule.modulestore.mongo.MongoModuleStore",54 "OPTIONS": {55 "collection": "modulestore",56 "db": "test",57 "default_class": "xmodule.hidden_module.HiddenDescriptor",58 }59 },60 "default": {61 "ENGINE": "the_default_store",62 "OPTIONS": {63 "option1": "value1",64 "option2": "value2"65 },66 "DOC_STORE_CONFIG": {}67 },68 "xml": {69 "ENGINE": "xmodule.modulestore.xml.XMLModuleStore",70 "OPTIONS": {71 "data_dir": "directory",72 "default_class": "xmodule.hidden_module.HiddenDescriptor"73 },74 "DOC_STORE_CONFIG": {}75 }76 }77 }78 }79 }80 ALREADY_UPDATED_MIXED_CONFIG = {81 'default': {82 'ENGINE': 'xmodule.modulestore.mixed.MixedModuleStore',83 'OPTIONS': {84 'mappings': {},85 'stores': [86 {87 'NAME': 'split',88 'ENGINE': 'xmodule.modulestore.split_mongo.split_draft.DraftVersioningModuleStore',89 'DOC_STORE_CONFIG': {},90 'OPTIONS': {91 'default_class': 'xmodule.hidden_module.HiddenDescriptor',92 'fs_root': "fs_root",93 'render_template': 'edxmako.shortcuts.render_to_string',94 }95 },96 {97 'NAME': 'draft',98 'ENGINE': 'xmodule.modulestore.mongo.draft.DraftModuleStore',99 'DOC_STORE_CONFIG': {},100 'OPTIONS': {101 'default_class': 'xmodule.hidden_module.HiddenDescriptor',102 'fs_root': "fs_root",103 'render_template': 'edxmako.shortcuts.render_to_string',104 }105 },106 ]107 }108 }109 }110 def assertStoreValuesEqual(self, store_setting1, store_setting2):111 """112 Tests whether the fields in the given store_settings are equal.113 """114 store_fields = ["OPTIONS", "DOC_STORE_CONFIG"]115 for field in store_fields:116 self.assertEqual(store_setting1[field], store_setting2[field])117 def assertMigrated(self, old_setting):118 """119 Migrates the given setting and checks whether it correctly converted120 to an ordered list of stores within Mixed.121 """122 # pass a copy of the old setting since the migration modifies the given setting123 new_mixed_setting = convert_module_store_setting_if_needed(copy.deepcopy(old_setting))124 # check whether the configuration is encapsulated within Mixed.125 self.assertEqual(new_mixed_setting["default"]["ENGINE"], "xmodule.modulestore.mixed.MixedModuleStore")126 # check whether the stores are in an ordered list127 new_stores = get_mixed_stores(new_mixed_setting)128 self.assertIsInstance(new_stores, list)129 return new_mixed_setting, new_stores[0]130 def is_split_configured(self, mixed_setting):131 """132 Tests whether the split module store is configured in the given setting.133 """134 stores = get_mixed_stores(mixed_setting)135 split_settings = [store for store in stores if store['ENGINE'].endswith('.DraftVersioningModuleStore')]136 if len(split_settings):137 # there should only be one setting for split138 self.assertEquals(len(split_settings), 1)139 # verify name140 self.assertEquals(split_settings[0]['NAME'], 'split')141 # verify split config settings equal those of mongo142 self.assertStoreValuesEqual(143 split_settings[0],144 next((store for store in stores if 'DraftModuleStore' in store['ENGINE']), None)145 )146 return len(split_settings) > 0147 def test_convert_into_mixed(self):148 old_setting = self.OLD_CONFIG149 new_mixed_setting, new_default_store_setting = self.assertMigrated(old_setting)150 self.assertStoreValuesEqual(new_default_store_setting, old_setting["default"])151 self.assertEqual(new_default_store_setting["ENGINE"], old_setting["default"]["ENGINE"])152 self.assertFalse(self.is_split_configured(new_mixed_setting))153 def test_convert_from_old_mongo_to_draft_store(self):154 old_setting = self.OLD_CONFIG_WITH_DIRECT_MONGO155 new_mixed_setting, new_default_store_setting = self.assertMigrated(old_setting)156 self.assertStoreValuesEqual(new_default_store_setting, old_setting["default"])157 self.assertEqual(new_default_store_setting["ENGINE"], "xmodule.modulestore.mongo.draft.DraftModuleStore")158 self.assertTrue(self.is_split_configured(new_mixed_setting))159 def test_convert_from_dict_to_list(self):160 old_mixed_setting = self.OLD_MIXED_CONFIG_WITH_DICT161 new_mixed_setting, new_default_store_setting = self.assertMigrated(old_mixed_setting)162 self.assertEqual(new_default_store_setting["ENGINE"], "the_default_store")163 self.assertTrue(self.is_split_configured(new_mixed_setting))164 # exclude split when comparing old and new, since split was added as part of the migration165 new_stores = [store for store in get_mixed_stores(new_mixed_setting) if store['NAME'] != 'split']166 old_stores = get_mixed_stores(self.OLD_MIXED_CONFIG_WITH_DICT)167 # compare each store configured in mixed168 self.assertEqual(len(new_stores), len(old_stores))169 for new_store in new_stores:170 self.assertStoreValuesEqual(new_store, old_stores[new_store['NAME']])171 def test_no_conversion(self):172 # make sure there is no migration done on an already updated config173 old_mixed_setting = self.ALREADY_UPDATED_MIXED_CONFIG174 new_mixed_setting, new_default_store_setting = self.assertMigrated(old_mixed_setting)175 self.assertTrue(self.is_split_configured(new_mixed_setting))176 self.assertEquals(old_mixed_setting, new_mixed_setting)177 @ddt.data('draft', 'split')178 def test_update_settings(self, default_store):179 mixed_setting = self.ALREADY_UPDATED_MIXED_CONFIG180 update_module_store_settings(mixed_setting, default_store=default_store)181 self.assertTrue(get_mixed_stores(mixed_setting)[0]['NAME'] == default_store)182 def test_update_settings_error(self):183 mixed_setting = self.ALREADY_UPDATED_MIXED_CONFIG184 with self.assertRaises(Exception):...

Full Screen

Full Screen

modulestore_settings.py

Source:modulestore_settings.py Github

copy

Full Screen

1"""2This file contains helper functions for configuring module_store_setting settings and support for backward compatibility with older formats.3"""4import warnings5import copy6def convert_module_store_setting_if_needed(module_store_setting):7 """8 Converts old-style module_store_setting configuration settings to the new format.9 """10 def convert_old_stores_into_list(old_stores):11 """12 Converts and returns the given stores in old (unordered) dict-style format to the new (ordered) list format13 """14 new_store_list = []15 for store_name, store_settings in old_stores.iteritems():16 store_settings['NAME'] = store_name17 if store_name == 'default':18 new_store_list.insert(0, store_settings)19 else:20 new_store_list.append(store_settings)21 # migrate request for the old 'direct' Mongo store to the Draft store22 if store_settings['ENGINE'] == 'xmodule.modulestore.mongo.MongoModuleStore':23 warnings.warn("MongoModuleStore is deprecated! Please use DraftModuleStore.", DeprecationWarning)24 store_settings['ENGINE'] = 'xmodule.modulestore.mongo.draft.DraftModuleStore'25 return new_store_list26 if module_store_setting is None:27 return None28 # Convert to Mixed, if needed29 if module_store_setting['default']['ENGINE'] != 'xmodule.modulestore.mixed.MixedModuleStore':30 warnings.warn("Direct access to a modulestore is deprecated. Please use MixedModuleStore.", DeprecationWarning)31 # convert to using mixed module_store32 new_module_store_setting = {33 "default": {34 "ENGINE": "xmodule.modulestore.mixed.MixedModuleStore",35 "OPTIONS": {36 "mappings": {},37 "stores": []38 }39 }40 }41 # copy the old configurations into the new settings42 new_module_store_setting['default']['OPTIONS']['stores'] = convert_old_stores_into_list(43 module_store_setting44 )45 module_store_setting = new_module_store_setting46 # Convert from dict, if needed47 elif isinstance(get_mixed_stores(module_store_setting), dict):48 warnings.warn(49 "Using a dict for the Stores option in the MixedModuleStore is deprecated. Please use a list instead.",50 DeprecationWarning51 )52 # convert old-style (unordered) dict to (an ordered) list53 module_store_setting['default']['OPTIONS']['stores'] = convert_old_stores_into_list(54 get_mixed_stores(module_store_setting)55 )56 assert isinstance(get_mixed_stores(module_store_setting), list)57 # Add Split, if needed58 # If Split is not defined but the DraftMongoModuleStore is configured, add Split as a copy of Draft59 mixed_stores = get_mixed_stores(module_store_setting)60 is_split_defined = any((store['ENGINE'].endswith('.DraftVersioningModuleStore')) for store in mixed_stores)61 if not is_split_defined:62 # find first setting of mongo store63 mongo_store = next(64 (store for store in mixed_stores if (65 store['ENGINE'].endswith('.DraftMongoModuleStore') or store['ENGINE'].endswith('.DraftModuleStore')66 )),67 None68 )69 if mongo_store:70 # deepcopy mongo -> split71 split_store = copy.deepcopy(mongo_store)72 # update the ENGINE and NAME fields73 split_store['ENGINE'] = 'xmodule.modulestore.split_mongo.split_draft.DraftVersioningModuleStore'74 split_store['NAME'] = 'split'75 # add split to the end of the list76 mixed_stores.append(split_store)77 return module_store_setting78def update_module_store_settings(79 module_store_setting,80 doc_store_settings=None,81 module_store_options=None,82 xml_store_options=None,83 default_store=None,84):85 """86 Updates the settings for each store defined in the given module_store_setting settings87 with the given doc store configuration and options, overwriting existing keys.88 If default_store is specified, the given default store is moved to the top of the89 list of stores.90 """91 for store in module_store_setting['default']['OPTIONS']['stores']:92 if store['NAME'] == 'xml':93 xml_store_options and store['OPTIONS'].update(xml_store_options)94 else:95 module_store_options and store['OPTIONS'].update(module_store_options)96 doc_store_settings and store['DOC_STORE_CONFIG'].update(doc_store_settings)97 if default_store:98 mixed_stores = get_mixed_stores(module_store_setting)99 for store in mixed_stores:100 if store['NAME'] == default_store:101 # move the found store to the top of the list102 mixed_stores.remove(store)103 mixed_stores.insert(0, store)104 return105 raise Exception("Could not find setting for requested default store: {}".format(default_store))106def get_mixed_stores(mixed_setting):107 """108 Helper for accessing stores in a configuration setting for the Mixed modulestore.109 """...

Full Screen

Full Screen

windows.py

Source:windows.py Github

copy

Full Screen

...58 yield store59 finally:60 flag = CERT_CLOSE_STORE_FORCE_FLAG if force_close else 061 if ctype:62 crypt32.CertCloseStore(store, flag)63 else:64 store.CertCloseStore(flag)65def install_ca(ca_cert: crypto.X509):66 store_name = "Root"67 logger.info("Installing CA '%s' into '%s' store", ca_cert.get_subject().CN, store_name)68 with _open_cert_store(store_name) as store:69 store.CertAddEncodedCertificateToStore(70 X509_ASN_ENCODING, crypto.dump_certificate(crypto.FILETYPE_ASN1, ca_cert), CERT_STORE_ADD_REPLACE_EXISTING71 )72def load_ca(subject_name: str) -> crypto.X509:73 store_name = "Root"74 logger.debug("Trying to find %s in certificate store", subject_name)75 with _open_cert_store(store_name, force_close=False) as store:76 for certificate in store.CertEnumCertificatesInStore():77 # logger.trace("checking certificate %s", certificate.SerialNumber) # ASN1 encoded integer78 ca_cert = crypto.load_certificate(crypto.FILETYPE_ASN1, certificate.CertEncoded)79 logger.trace("checking certificate %s", ca_cert.get_subject().CN)80 if ca_cert.get_subject().CN == subject_name:81 logger.debug("Found matching ca %s", subject_name)82 return ca_cert83 logger.debug("Did not find ca")84 return None85def remove_ca(subject_name: str) -> bool:86 store_name = "Root"87 removed = 088 with _open_cert_store(store_name, ctype=True) as store:89 while True:90 p_cert_ctx = crypt32.CertFindCertificateInStore(91 store,92 X509_ASN_ENCODING,93 0,94 CERT_FIND_SUBJECT_STR, # Searches for a certificate that contains the specified subject name string95 subject_name,96 None,97 )98 if p_cert_ctx == 0:99 break100 cbsize = crypt32.CertGetNameStringW(p_cert_ctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, None, 0)101 buf = ctypes.create_unicode_buffer(cbsize)102 cbsize = crypt32.CertGetNameStringW(p_cert_ctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE, 0, None, buf, cbsize)103 logger.info("Removing CA '%s' (%s) from '%s' store", subject_name, buf.value, store_name)104 crypt32.CertDeleteCertificateFromStore(p_cert_ctx)105 crypt32.CertFreeCertificateContext(p_cert_ctx)106 removed += 1107 if removed >= 25:108 raise RuntimeError(f"Stop loop after removing {removed} certficates")109 if not removed:110 # Cert not found111 logger.info("CA '%s' not found in store '%s', nothing to remove", subject_name, store_name)112 return False...

Full Screen

Full Screen

liteaxolotlstore.py

Source:liteaxolotlstore.py Github

copy

Full Screen

...4from .litesessionstore import LiteSessionStore5from .litesignedprekeystore import LiteSignedPreKeyStore6from .litesenderkeystore import LiteSenderKeyStore7import sqlite38class LiteAxolotlStore(AxolotlStore):9 def __init__(self, db):10 conn = sqlite3.connect(db, check_same_thread=False)11 conn.text_factory = bytes12 self.identityKeyStore = LiteIdentityKeyStore(conn)13 self.preKeyStore = LitePreKeyStore(conn)14 self.signedPreKeyStore = LiteSignedPreKeyStore(conn)15 self.sessionStore = LiteSessionStore(conn)16 self.senderKeyStore = LiteSenderKeyStore(conn)17 def getIdentityKeyPair(self):18 return self.identityKeyStore.getIdentityKeyPair()19 def storeLocalData(self, registrationId, identityKeyPair):20 self.identityKeyStore.storeLocalData(registrationId, identityKeyPair)21 def getLocalRegistrationId(self):22 return self.identityKeyStore.getLocalRegistrationId()23 def saveIdentity(self, recepientId, identityKey):24 self.identityKeyStore.saveIdentity(recepientId, identityKey)25 def isTrustedIdentity(self, recepientId, identityKey):26 return self.identityKeyStore.isTrustedIdentity(recepientId, identityKey)27 def loadPreKey(self, preKeyId):28 return self.preKeyStore.loadPreKey(preKeyId)29 def loadPreKeys(self):30 return self.preKeyStore.loadPendingPreKeys()...

Full Screen

Full Screen

store.py

Source:store.py Github

copy

Full Screen

1from flask_restful import Resource2from models.store import StoreModel3from flask_jwt import jwt_required4class Store(Resource):5 def get(self, name):6 store = StoreModel.find_by_name(name)7 if store:8 return store.json()9 return {"message": "Store not found"}, 40410 @jwt_required() 11 def post(self, name):12 store = StoreModel.find_by_name(name)13 if store:14 return {"Store already exists"}, 40015 store = StoreModel(name)16 try:17 store.save_to_db()18 except:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Store = require('istanbul').Store;2var store = new Store();3var CoverageMap = require('istanbul').CoverageMap;4var map = new CoverageMap();5var Collector = require('istanbul').Collector;6var collector = new Collector();7var Reporter = require('istanbul').Reporter;8var reporter = new Reporter();9var Report = require('istanbul').Report;10var report = new Report();11var Hook = require('istanbul').Hook;12var hook = new Hook();13var Instrumenter = require('istanbul').Instrumenter;14var instrumenter = new Instrumenter();15var Visitor = require('istanbul').Visitor;16var visitor = new Visitor();17var utils = require('istanbul').utils;18utils.addDerivedInfo();19var libReport = require('istanbul').libReport;20libReport.create('html');21var libCoverage = require('istanbul').libCoverage;22libCoverage.createCoverageMap();23var libHook = require('istanbul').libHook;24libHook.hookRunInThisContext();25var libInstrument = require('istanbul').libInstrument;26libInstrument.createInstrumenter();27var libSourceMaps = require('istanbul').libSourceMaps;28libSourceMaps.createSourceMapStore();29var libUtil = require('istanbul').libUtil;30libUtil.canInstrument();31var libVisitor = require('istanbul').libVisitor;32libVisitor.createVisitor();33var libReport = require('istanbul').libReport;34libReport.create('html');

Full Screen

Using AI Code Generation

copy

Full Screen

1var Store = require('istanbul').Store;2var store = new Store();3store.add({path: 'foo.js', coverage: {foo: 1}});4store.add({path: 'bar.js', coverage: {bar: 2}});5store.save('path/to/coverage.json', function () {6 console.log('done');7});8{9 "scripts": {10 },11 "dependencies": {12 },13 "devDependencies": {14 }15}

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbul = require('istanbul');2var collector = new istanbul.Collector();3var reporter = new istanbul.Reporter();4var sync = false;5collector.add(__coverage__);6reporter.add('lcov');7reporter.write(collector, sync, function () {8 console.log('write completed');9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var Store = require('istanbul').Store;2var store = new Store();3var coverage = require('./coverage.json');4store.add(coverage);5var Report = require('istanbul').Report;6var report = Report.create('lcovonly');7report.on('done', function () {8 console.log('done');9});10report.writeReport(store, {});11var Report = require('istanbul').Report;12var report = Report.create('html');13report.on('done', function () {14 console.log('done');15});16report.writeReport(store, {});17var Report = require('istanbul').Report;18var report = Report.create('text');19report.on('done', function () {20 console.log('done');21});22report.writeReport(store, {});23var Report = require('istanbul').Report;24var report = Report.create('text-summary');25report.on('done', function () {26 console.log('done');27});28report.writeReport(store, {});29{30 "scripts": {31 },32 "dependencies": {33 }34}

Full Screen

Using AI Code Generation

copy

Full Screen

1var istanbulMiddleware = require('istanbul-middleware');2var store = istanbulMiddleware.createStore();3store.addFileCoverage(coverageData);4var istanbulLibCoverage = require('istanbul-lib-coverage');5var store = istanbulLibCoverage.createCoverageMap();6store.merge(coverageData);7var istanbulLibSourceMaps = require('istanbul-lib-source-maps');8var store = istanbulLibSourceMaps.createSourceMapStore();9store.registerURL(url, sourceMap);10var istanbulReports = require('istanbul-reports');11var store = istanbulReports.create('html');12store.execute({});13var istanbulLibReport = require('istanbul-lib-report');14var store = istanbulLibReport.create('html');15store.execute({});16var istanbulLibInstrument = require('istanbul-lib-instrument');17var store = istanbulLibInstrument.createInstrumenter();18store.instrumentSync(code, filename);19var istanbulLibCoverage = require('istanbul-lib-coverage');20var store = istanbulLibCoverage.createCoverageMap();21store.merge(coverageData);22var istanbulLibReport = require('istanbul-lib-report');23var store = istanbulLibReport.create('html');24store.execute({});25var istanbulLibReport = require('istanbul-lib-report');26var store = istanbulLibReport.create('html');27store.execute({});28var istanbulLibCoverage = require('istanbul-lib-coverage');29var store = istanbulLibCoverage.createCoverageMap();30store.merge(coverageData);31var istanbulLibSourceMaps = require('istanbul-lib-source-maps');32var store = istanbulLibSourceMaps.createSourceMapStore();33store.registerURL(url, source

Full Screen

Using AI Code Generation

copy

Full Screen

1var Store = require('istanbul/lib/store/memory');2var store = new Store();3store.set('hello', 'world');4console.log(store.get('hello'));5var Store = require('istanbul/lib/store/memory');6var store = new Store();7store.set('hello', 'world');8console.log(store.get('hello'));9var Store = require('istanbul/lib/store/memory');10var store = new Store();11store.set('hello', 'world');12console.log(store.get('hello'));13var Store = require('istanbul/lib/store/memory');14var store = new Store();15store.set('hello', 'world');16console.log(store.get('hello'));17var Store = require('istanbul/lib/store/memory');18var store = new Store();19store.set('hello', 'world');20console.log(store.get('hello'));21var Store = require('istanbul/lib/store/memory');22var store = new Store();23store.set('hello', 'world');24console.log(store.get('hello'));25var Store = require('istanbul/lib/store/memory');26var store = new Store();27store.set('hello', 'world');28console.log(store.get('hello'));29var Store = require('istanbul/lib/store/memory');30var store = new Store();31store.set('hello', 'world');32console.log(store.get('hello'));33var Store = require('istanbul/lib/store/memory');34var store = new Store();35store.set('hello', 'world');36console.log(store.get('hello'));37var Store = require('istanbul/lib/store/memory');38var store = new Store();39store.set('hello', 'world');40console.log(store.get('hello'));41var Store = require('istanbul/lib

Full Screen

Using AI Code Generation

copy

Full Screen

1var Store = require('istanbul').Store;2var store = new Store();3store.add(coverage);4store.save('coverage.json', function () {5 console.log('Write coverage.json');6});7"scripts": {8}

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