How to use attached_files method in autotest

Best Python code snippet using autotest_python

attached_files.py

Source:attached_files.py Github

copy

Full Screen

...130 IOError: did not find file 'test.py' in load / attach search path131 sage: load_attach_path(t_dir)132 sage: attach('test.py')133 111134 sage: attached_files() == [fullpath]135 True136 sage: sage.misc.attached_files.reset(); reset_load_attach_path()137 sage: load_attach_path() == ['.']138 True139 sage: load('test.py')140 Traceback (most recent call last):141 ...142 IOError: did not find file 'test.py' in load / attach search path143 The function returns a reference to the path list::144 sage: reset_load_attach_path(); load_attach_path()145 ['.']146 sage: load_attach_path('/path/to/my/sage/scripts'); load_attach_path()147 ['.', '/path/to/my/sage/scripts']148 sage: load_attach_path(['good', 'bad', 'ugly'], replace=True)149 sage: load_attach_path()150 ['good', 'bad', 'ugly']151 sage: p = load_attach_path(); p.pop()152 'ugly'153 sage: p[0] = 'weird'; load_attach_path()154 ['weird', 'bad']155 sage: reset_load_attach_path(); load_attach_path()156 ['.']157 """158 global search_paths159 if path is None:160 return search_paths161 else:162 if isinstance(path, basestring):163 path = [path]164 if replace:165 search_paths = path166 else:167 for p in path:168 if not p:169 continue170 if p not in search_paths:171 search_paths.append(p)172def reset_load_attach_path():173 """174 Resets the current search path for :func:`load` and175 :func:`attach`.176 The default path is ``'.'`` plus any paths specified in the177 environment variable ``SAGE_LOAD_ATTACH_PATH``.178 EXAMPLES::179 sage: load_attach_path()180 ['.']181 sage: t_dir = tmp_dir()182 sage: load_attach_path(t_dir)183 sage: t_dir in load_attach_path()184 True185 sage: reset_load_attach_path(); load_attach_path()186 ['.']187 At startup, Sage adds colon-separated paths in the environment188 variable ``SAGE_LOAD_ATTACH_PATH``::189 sage: reset_load_attach_path(); load_attach_path()190 ['.']191 sage: os.environ['SAGE_LOAD_ATTACH_PATH'] = '/veni/vidi:vici:'192 sage: reload(sage.misc.attached_files) # Simulate startup193 <module 'sage.misc.attached_files' from '...'>194 sage: load_attach_path()195 ['.', '/veni/vidi', 'vici']196 sage: del os.environ['SAGE_LOAD_ATTACH_PATH']197 sage: reload(sage.misc.preparser) # Simulate startup198 <module 'sage.misc.preparser' from '...'>199 sage: reset_load_attach_path(); load_attach_path()200 ['.']201 """202 global search_paths203 search_paths = ['.']204 for path in os.environ.get('SAGE_LOAD_ATTACH_PATH', '').split(':'):205 load_attach_path(path=path)206# Set up the initial search path for loading and attaching files. A207# user can modify the path with the function load_attach_path.208reset_load_attach_path()209def attach(*files):210 """211 Attach a file or files to a running instance of Sage and also load212 that file.213 USAGE:214 ``attach file1 ...`` - space-separated list of ``.py``, ``.pyx``,215 and ``.sage`` files, or ``attach('file1', 'file2')`` - filenames as216 strings, given as arguments to :func:`attach`.217 :meth:`~sage.misc.preparser.load` is the same as :func:`attach`, but218 doesn't automatically reload a file when it changes.219 .. NOTE::220 On the Sage prompt you can also just type ``attach "foo.sage"``221 as a short-hand for ``attach('foo.sage')``. However this222 alternate form is not part of the Python language and does not223 work in Python scripts.224 EFFECT:225 Each file is read in and added to an internal list of watched files.226 The meaning of reading in a file depends on the file type:227 - ``.py`` files are read in with no preparsing (so, e.g., ``2^3`` is 2228 bit-xor 3);229 - ``.sage`` files are preparsed, then the result is read in;230 - ``.pyx`` files are *not* preparsed, but rather are compiled to a231 module ``m`` and then ``from m import *`` is executed.232 The contents of the file are then loaded, which means they are read233 into the running Sage session. For example, if ``foo.sage`` contains234 ``x=5``, after attaching ``foo.sage`` the variable ``x`` will be set235 to 5. Moreover, any time you change ``foo.sage``, before you execute236 a command, the attached file will be re-read automatically (with no237 intervention on your part).238 EXAMPLES:239 You attach a file, e.g., ``foo.sage`` or ``foo.py`` or240 ``foo.pyx``, to a running Sage session by typing::241 sage: attach foo.sage # or foo.py or foo.pyx or even a URL to such a file (not tested)242 or::243 sage: attach('foo.sage') # not tested244 Here we test attaching multiple files at once::245 sage: sage.misc.attached_files.reset()246 sage: t1 = tmp_filename(ext='.py')247 sage: open(t1,'w').write("print 'hello world'")248 sage: t2 = tmp_filename(ext='.py')249 sage: open(t2,'w').write("print 'hi there xxx'")250 sage: attach(t1, t2)251 hello world252 hi there xxx253 sage: set(attached_files()) == set([t1,t2])254 True255 .. SEEALSO::256 - :meth:`attached_files` returns a list of257 all currently attached files.258 - :meth:`detach` instructs Sage to remove a259 file from the internal list of watched files.260 - :meth:`load_attach_path` allows you to261 get or modify the current search path for loading and attaching262 files.263 """264 try:265 ipy = get_ipython()266 except NameError:267 ipy = None268 global attached269 for filename in files:270 if ipy:271 code = load_wrap(filename, attach=True)272 ipy.run_cell(code)273 else:274 load(filename, globals(), attach=True)275def add_attached_file(filename):276 """277 Add to the list of attached files278 This is a callback to be used from279 :func:`~sage.misc.preparse.load` after evaluating the attached280 file the first time.281 INPUT:282 - ``filename`` -- string, the fully qualified file name.283 EXAMPLES::284 sage: import sage.misc.attached_files as af285 sage: af.reset()286 sage: t = tmp_filename(ext='.py')287 sage: af.add_attached_file(t)288 sage: af.attached_files()289 ['/.../tmp_....py']290 sage: af.detach(t)291 sage: af.attached_files()292 []293 """294 fpath = os.path.abspath(filename)295 attached[fpath] = os.path.getmtime(fpath)296def attached_files():297 """298 Returns a list of all files attached to the current session with299 :meth:`attach`.300 OUTPUT:301 The filenames in a sorted list of strings.302 EXAMPLES::303 sage: sage.misc.attached_files.reset()304 sage: t = tmp_filename(ext='.py')305 sage: open(t,'w').write("print 'hello world'")306 sage: attach(t)307 hello world308 sage: attached_files()309 ['/....py']310 sage: attached_files() == [t]311 True312 """313 global attached314 return list(sorted(attached.keys()))315def detach(filename):316 """317 Detach a file.318 This is the counterpart to :meth:`attach`.319 INPUT:320 - ``filename`` -- a string, or a list of strings, or a tuple of strings.321 EXAMPLES::322 sage: sage.misc.attached_files.reset()323 sage: t = tmp_filename(ext='.py')324 sage: open(t,'w').write("print 'hello world'")325 sage: attach(t)326 hello world327 sage: attached_files() == [t]328 True329 sage: detach(t)330 sage: attached_files()331 []332 sage: sage.misc.attached_files.reset(); reset_load_attach_path()333 sage: load_attach_path()334 ['.']335 sage: t_dir = tmp_dir()336 sage: fullpath = os.path.join(t_dir, 'test.py')337 sage: open(fullpath, 'w').write("print 37 * 3")338 sage: load_attach_path(t_dir)339 sage: attach('test.py')340 111341 sage: attached_files() == [os.path.normpath(fullpath)]342 True343 sage: detach('test.py')344 sage: attached_files()345 []346 sage: attach('test.py')347 111348 sage: fullpath = os.path.join(t_dir, 'test2.py')349 sage: open(fullpath, 'w').write("print 3")350 sage: attach('test2.py')351 3352 sage: detach(attached_files())353 sage: attached_files()354 []355 TESTS::356 sage: detach('/dev/null/foobar.sage')357 Traceback (most recent call last):358 ...359 ValueError: file '/dev/null/foobar.sage' is not attached, see attached_files()360 """361 if isinstance(filename, basestring):362 filelist = [filename]363 else:364 filelist = [str(x) for x in filename]365 global attached366 for filename in filelist:367 fpath = os.path.expanduser(filename)368 if not os.path.isabs(fpath):369 for path in load_attach_path():370 epath = os.path.expanduser(path)371 fpath = os.path.join(epath, filename)372 fpath = os.path.abspath(fpath)373 if fpath in attached:374 break375 if fpath in attached:376 attached.pop(fpath)377 else:378 raise ValueError("file '{0}' is not attached, see attached_files()".format(filename))379def reset():380 """381 Remove all the attached files from the list of attached files.382 EXAMPLES::383 sage: sage.misc.attached_files.reset()384 sage: t = tmp_filename(ext='.py')385 sage: open(t,'w').write("print 'hello world'")386 sage: attach(t)387 hello world388 sage: attached_files() == [t]389 True390 sage: sage.misc.attached_files.reset()391 sage: attached_files()392 []393 """394 global attached395 attached = {}396def modified_file_iterator():397 """398 Iterate over the changed files399 As a side effect the stored time stamps are updated with the400 actual time stamps. So if you iterate over the attached files in401 order to reload them and you hit an error then the subsequent402 files are not marked as read.403 Files that are in the process of being saved are excluded.404 EXAMPLES::405 sage: sage.misc.attached_files.reset()406 sage: t = tmp_filename(ext='.py')407 sage: attach(t)408 sage: from sage.misc.attached_files import modified_file_iterator409 sage: list(modified_file_iterator())410 []411 sage: sleep(1) # filesystem mtime granularity412 sage: open(t, 'w').write('1')413 sage: list(modified_file_iterator())414 [('/.../tmp_....py', time.struct_time(...))]415 """416 global attached417 modified = dict()418 for filename in attached.keys():419 old_tm = attached[filename]420 if not os.path.exists(filename):421 print '### detaching file {0} because it does not exist (deleted?) ###'.format(filename)422 detach(filename)423 continue424 new_tm = os.path.getmtime(filename)425 if new_tm > old_tm:426 modified[filename] = new_tm427 if not modified:428 return429 time.sleep(0.1) # sleep 100ms to give the editor time to finish saving430 for filename in modified.keys():431 old_tm = modified[filename]432 new_tm = os.path.getmtime(filename)433 if new_tm == old_tm:434 # file was modified but did not change in the last 100ms435 attached[filename] = new_tm436 yield filename, time.gmtime(new_tm)437def reload_attached_files_if_modified():438 """439 Reload attached files that have been modified440 This is the internal implementation of the attach mechanism.441 EXAMPLES::442 sage: sage.misc.attached_files.reset()443 sage: from sage.misc.interpreter import get_test_shell444 sage: shell = get_test_shell()445 sage: tmp = tmp_filename(ext='.py')446 sage: open(tmp, 'w').write('a = 2\n')447 sage: shell.run_cell('attach({0})'.format(repr(tmp)))448 sage: shell.run_cell('a')449 2450 sage: sleep(1) # filesystem mtime granularity451 sage: open(tmp, 'w').write('a = 3\n')452 Note that the doctests are never really at the command prompt453 where the automatic reload is triggered. So we have to do it454 manually::455 sage: shell.run_cell('from sage.misc.attached_files import reload_attached_files_if_modified')456 sage: shell.run_cell('reload_attached_files_if_modified()')457 ### reloading attached file tmp_....py modified at ... ###458 sage: shell.run_cell('a')459 3460 sage: shell.run_cell('detach({0})'.format(repr(tmp)))461 sage: shell.run_cell('attached_files()')462 []463 """464 for filename, mtime in modified_file_iterator():465 basename = os.path.basename(filename)466 timestr = time.strftime('%T', mtime)467 from sage.libs.readline import interleaved_output468 with interleaved_output():469 print '### reloading attached file {0} modified at {1} ###'.format(basename, timestr)470 code = load_wrap(filename, attach=True)...

Full Screen

Full Screen

akidump.py

Source:akidump.py Github

copy

Full Screen

1#!/usr/bin/env python32# Copyright (c) 2020-2021. Bohdan Kolvakh3# This file is part of PyQtAccounts.4#5# PyQtAccounts is free software: you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation, either version 3 of the License, or8# (at your option) any later version.9#10# PyQtAccounts is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with PyQtAccounts. If not, see <https://www.gnu.org/licenses/>.17#18# PyQtAccounts is free software: you can redistribute it and/or modify19# it under the terms of the GNU General Public License as published by20# the Free Software Foundation, either version 3 of the License, or21# (at your option) any later version.22#23# PyQtAccounts is distributed in the hope that it will be useful,24# but WITHOUT ANY WARRANTY; without even the implied warranty of25# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the26# GNU General Public License for more details.27#28# You should have received a copy of the GNU General Public License29# along with PyQtAccounts. If not, see <https://www.gnu.org/licenses/>.30# PyQtAccounts is free software: you can redistribute it and/or modify31# it under the terms of the GNU General Public License as published by32# the Free Software Foundation, either version 3 of the License, or33# (at your option) any later version.34# PyQtAccounts is distributed in the hope that it will be useful,35# but WITHOUT ANY WARRANTY; without even the implied warranty of36# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the37# GNU General Public License for more details.38# You should have received a copy of the GNU General Public License39# along with PyQtAccounts. If not, see <https://www.gnu.org/licenses/>.40"""41This module provides functions and classes for serializing and deserializing accounts.42This module has replaced pickle module from standard library because of security reasons.43"""44import json45import base6446# NOTE: this separator is now obsolete because we use json to serialize our databases47SEPARATOR = "s" + "-=" * 30 + "e" # this is a separator between accounts in .db file.48class Account:49 """50 This class stores data about account.51 """52 def __init__(53 self,54 account,55 name,56 email,57 password,58 date,59 comment,60 copy_email=True,61 attach_files=None,62 ):63 """64 This constructor saves all account data.65 """66 self.account = account67 self.name = name68 self.email = email69 self.password = password70 self.date = date71 self.comment = comment72 self.copy_email = copy_email73 # here we check whether attached_files argument is supplied if yes we74 # assign it to self.attached_files attribute else we assign empty75 # dictionary to self.attached_files76 # NOTE: that we do this in that strange way because we dict is mutable77 # type and we can't just write attached_files={} in __init__ constructor78 self.attached_files = attach_files if attach_files else {}79 def __eq__(self, other):80 """81 This method compares attributes of two accounts and returns True if all of them are equal.82 """83 attrs = (84 "account",85 "name",86 "email",87 "password",88 "date",89 "comment",90 "copy_email",91 "attached_files",92 )93 for a in attrs:94 my = getattr(self, a)95 his = getattr(other, a)96 if my != his:97 return False98 else:99 return True100 def to_dict(self):101 """102 We use this method to convert our Account instance to dictionary which103 is json serializable.104 """105 # JSON can't encode byte like strings which we have in our106 # attached_files dict, so we encode those byte strings to ascii using107 # b64encode108 attach = {}109 for file in self.attached_files:110 encoded = base64.b64encode(self.attached_files[file])111 attach[file] = encoded.decode("ascii")112 return {113 "account": self.account,114 "name": self.name,115 "email": self.email,116 "password": self.password.decode(),117 "date": self.date,118 "comment": self.comment,119 "copy_email": self.copy_email,120 "attach_files": attach,121 }122def dumps(data):123 """124 This function serializes database to string using json module.125 :param data:126 represents database, type: dict127 :return:128 serialized string, type: byte string129 """130 db = {}131 for account in data:132 db[account] = data[account].to_dict()133 return json.dumps(db).encode()134def loads_old(data):135 """136 This function deserializes string to database.137 NOTE: this function is obsolete but we use it only for backward138 comparability with those databases that are serialized in obsolete way.139 :param data:140 string to deserialize, type: byte string141 :return:142 database, type: dict143 """144 data = data.decode().split(SEPARATOR)145 formated_data = []146 part = []147 for i, line in enumerate(data):148 part.append(line)149 if (int(i) + 1) % 6 == 0:150 formated_data.append(part[:])151 part = []152 res = {}153 for accountname, name, email, password, date, comment in formated_data:154 account = Account(accountname, name, email, password.encode(), date, comment)155 res[accountname] = account156 return res157def loads_json(data):158 """159 This function deserializes json string to database.160 :param data:161 json string to deserialize162 """163 # here db will be a dict which will contain dicts that will represent our164 # Account instances165 db = json.loads(data)166 # here we convert dicts in `db` to Account instances167 for account in db:168 # here we first encode password value of account dict to byte string,169 # because password in Account class must be a byte string170 password = db[account]["password"].encode()171 db[account]["password"] = password172 # here we also recode attached files from ascii base64 to byte string if173 # account have any174 attached_files = db[account].get("attach_files")175 if attached_files:176 for file in attached_files:177 data = attached_files[file].encode()178 recoded = base64.b64decode(data)179 db[account]["attach_files"][file] = recoded180 # then we unpack account dict as arguments for Account constructor to181 # create Account instance from account dict, then we save freshly182 # created Account instance back to the database183 db[account] = Account(**db[account])184 # finally we return deserialized database185 return db186def loads(data):187 """188 This function is an interface to `loads_old` and `loads_json` functions.189 `loads` will use `loads_old` for databases serialized in the190 obsolete way and `loads_json` for those serialized json way.191 """192 # here we first try to deserialize `data` using `loads_json`193 try:194 db = loads_json(data)195 except json.decoder.JSONDecodeError:196 # and if we cant decode that data, then perhaps it is database197 # serialized in the obsolete way, so we try `loads_old` to deserialize198 # it199 db = loads_old(data)200 # finally we return deserialized database...

Full Screen

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