Best Python code snippet using Contexts
test_lineage.py
Source:test_lineage.py  
...58        self.assertEqual(expected, checked)59    @responses.activate60    def test_read_lineage_template_and_populate_controls(self):61        checked = self.setup_and_call_lineage('-f {} innskudd'.format(62            resolve_filename('selected_innskudd_lineage.json')))63        expected = ['<b>kontonummer</b>',64                    "Label(value='/skatt/person')",65                    "Checkbox(value=True, description='kontonummer (*)'",66                    "Checkbox(value=False, description='personidentifikator'",67                    "Label(value='/skatt/konto')",68                    "Checkbox(value=True, description='kontonummer (*)'",69                    "Checkbox(value=False, description='innskudd'",70                    "Label(value='/skatt/unrelated')",71                    "Checkbox(value=False, description='weird'",72                    "Checkbox(value=False, description='stuff'",73                    '<b>personidentifikator</b>',74                    "Label(value='/skatt/person')",75                    "Checkbox(value=True, description='personidentifikator (*)'",76                    "Checkbox(value=False, description='kontonummer'",77                    "Label(value='/skatt/konto')",78                    "Checkbox(value=False, description='kontonummer'",79                    "Checkbox(value=False, description='innskudd'",80                    "Label(value='/skatt/unrelated')",81                    "Checkbox(value=False, description='weird'",82                    "Checkbox(value=False, description='stuff'",83                    '<b>innskudd</b>',84                    "Label(value='/skatt/person')",85                    "Checkbox(value=False, description='personidentifikator'",86                    "Checkbox(value=False, description='kontonummer'",87                    "Label(value='/skatt/konto')",88                    "Checkbox(value=True, description='innskudd (*)'",89                    "Checkbox(value=False, description='kontonummer'",90                    "Label(value='/skatt/unrelated')",91                    "Checkbox(value=False, description='weird'",92                    "Checkbox(value=False, description='stuff'"]93        self.assertEqual(expected, checked)94    @responses.activate95    def test_read_lineage_template_and_populate_controls_only_skatt_konto_should_be_selected(self):96        checked = self.setup_and_call_lineage('-f {} innskudd '.format(97            resolve_filename('selected_only_skatt_konto_innskudd_lineage.json')))98        expected = ['<b>kontonummer</b>',99                    "Label(value='/skatt/person')",100                    "Checkbox(value=False, description='kontonummer (*)'",101                    "Checkbox(value=False, description='personidentifikator'",102                    "Label(value='/skatt/konto')",103                    "Checkbox(value=True, description='kontonummer (*)'",104                    "Checkbox(value=False, description='innskudd'",105                    "Label(value='/skatt/unrelated')",106                    "Checkbox(value=False, description='weird'",107                    "Checkbox(value=False, description='stuff'",108                    '<b>personidentifikator</b>',109                    "Label(value='/skatt/person')",110                    "Checkbox(value=True, description='personidentifikator (*)'",111                    "Checkbox(value=False, description='kontonummer'",112                    "Label(value='/skatt/konto')",113                    "Checkbox(value=False, description='kontonummer'",114                    "Checkbox(value=False, description='innskudd'",115                    "Label(value='/skatt/unrelated')",116                    "Checkbox(value=False, description='weird'",117                    "Checkbox(value=False, description='stuff'",118                    '<b>innskudd</b>',119                    "Label(value='/skatt/person')",120                    "Checkbox(value=False, description='personidentifikator'",121                    "Checkbox(value=False, description='kontonummer'",122                    "Label(value='/skatt/konto')",123                    "Checkbox(value=True, description='innskudd (*)'",124                    "Checkbox(value=False, description='kontonummer'",125                    "Label(value='/skatt/unrelated')",126                    "Checkbox(value=False, description='weird'",127                    "Checkbox(value=False, description='stuff'"]128        self.assertEqual(expected, checked)129    @responses.activate130    def test_create_default_file_when_missing_filename_args(self):131        self.setup_and_call_lineage('innskudd')132        file_name = 'lineage_innskudd.json'133        if os.path.isfile(file_name):134            print(file_name)135            os.remove(file_name)136        else:137            self.fail("expected file not created {}".format(file_name))138    def setup_and_call_lineage(self, linage_args):139        with open(resolve_filename('lineage_template.json'), 'r') as f:140            lineage_template = json.load(f)141        responses.add(responses.POST, 'http://mock.no/lineage/template',142                      json=lineage_template, status=200)143        # Create 3 input datasets144        person_type = StructType([145            StructField('personidentifikator', StringType()),146            StructField('kontonummer', StringType())])147        person = self._spark.createDataFrame([], person_type)148        unrelated_type = StructType([149            StructField('weird', StringType()),150            StructField('stuff', StringType())])151        unrelated = self._spark.createDataFrame([], unrelated_type)152        konto_type = StructType([153            StructField('kontonummer', StringType()),154            StructField('innskudd', IntegerType())])155        konto = self._spark.createDataFrame([], konto_type)156        # Register inputs157        self._magic.input('', '/skatt/person\n/skatt/konto\n/skatt/unrelated')158        # Load inputs159        self._magic.on_input_load('/skatt/person {} {}'.format(1111, person.schema.json()))160        self._magic.on_input_load('/skatt/konto {} {}'.format(1111, konto.schema.json()))161        self._magic.on_input_load('/skatt/unrelated {} {}'.format(1111, unrelated.schema.json()))162        # Output dataset163        innskudd = person.join(konto, 'kontonummer', how='inner')164        self._magic.shell.user_ns = {"innskudd": innskudd}165        # Run the lineage magic166        self._magic.lineage(linage_args)167        # Capture the display output168        captor = StringIO()169        print(*self._magic.display.call_args[0], file=captor, flush=True)170        controls = captor.getvalue()171        regexp = "<b>\w+</b>|Label\(value='/\w+/\w+'\)|Checkbox\(value=\w{4}\w?, description='\w+(?:.{4})?'"172        return re.findall(regexp, controls)173    def test_parse_options(self):174        opts, args = self._magic.parse_options('', '', 'append')175        self.assertFalse('append' in opts)176        opts, args = self._magic.parse_options('--append', '', 'append')177        self.assertTrue('append' in opts)178    def test_disable_input_warning(self):179        self.assertTrue(self._magic._show_warning_input)180        self._magic.input_warning('off')181        self.assertFalse(self._magic._show_warning_input)182        self._magic.input_warning('on')183        self.assertTrue(self._magic._show_warning_input)184    def test_disable_output_warning(self):185        self.assertTrue(self._magic._show_warning_output)186        self._magic.output_warning('False')187        self.assertFalse(self._magic._show_warning_output)188        self._magic.output_warning('True')189        self.assertTrue(self._magic._show_warning_output)190    def test_lineage_output(self):191        with open(resolve_filename('selected_innskudd_lineage.json'), 'r') as f:192            lineage_template = json.load(f)193        with open(resolve_filename('lineage_output.json'), 'r') as f:194            expected_lineage = json.load(f)195        output = map_lineage(lineage_template)196        self.assertEqual(expected_lineage, output)197    def test_lineage_output_no_source(self):198        with open(resolve_filename('lineage_template_no_source.json'), 'r') as f:199            lineage_template = json.load(f)200        with open(resolve_filename('lineage_output_no_source.json'), 'r') as f:201            expected_lineage = json.load(f)202        output = map_lineage(lineage_template)...Resolver.py
Source:Resolver.py  
...38                base URL or filename of the file through the ``base_url``39                keyword argument.  If the ``close`` flag is True (the40                default), the file will be closed after reading.41        42                Note that using ``.resolve_filename()`` is more efficient,43                especially in threaded environments.44        """45        pass46    def resolve_filename(self, filename, context): # real signature unknown; restored from __doc__47        """48        resolve_filename(self, filename, context)49        50                Return the name of a parsable file as input document.51        52                Pass filename and context as parameters.  You can also pass a53                URL with an HTTP, FTP or file target.54        """55        pass56    def resolve_string(self, string, context, base_url=None): # real signature unknown; restored from __doc__57        """58        resolve_string(self, string, context, base_url=None)59        60                Return a parsable string as input document.61        62                Pass data string and context as parameters.  You can pass the...tinydb-example.py
Source:tinydb-example.py  
...31		save the list into the database. doing like a blob save. eg, saving the list32		contents under a single key, rather than saving the lines of the list33		'''34		35		fn = self.resolve_filename(filename)36		if not fn:37			warnings.warn('The list not saved as a filename has never been set')38			return      # no filename has been set39			40		db = TinyDB(fn)41		el = db.get(self.query.key == (fn))42		if el:43			db.update({'data':self[:]}, eids=[el.eid])44		else:45			e = db.insert({'key':self.filename, 'data': self[:]})46		db.close()47		48	def load(self, filename=None):49		fn = self.resolve_filename(filename)50		if not fn : return51		52		db = TinyDB(fn)53		el = db.get(self.query.key == (fn))54		if el.eid:55			self[:]= el['data']56		db.close()57		58	#def resolve_filename(self, filename=None):59		#if not filename:60			#if not self.filename:61				#return62			#else:63				#return self.filename64		#else:65			#return filename66	67	def resolve_filename(self, filename=None):68		return filename or self.filename or None69			70			71if __name__ == '__main__':72	fn = 'astro_turf.json'73	l2 = ListPersitant(fn)74	l2.append('a')75	l2.append('b')76	l2.append('c')77	l2.append('d')78	l2.append('hhh')79	l2.save()80	81	# print out the db...extract.py
Source:extract.py  
...12def is_zipinfo_dir(info: zipfile.ZipInfo) -> bool:13    is_msdos_dir = bool(info.external_attr & 0x10)14    is_unix_dir = bool(is_extended_mode_dir(info.external_attr >> 16))15    return is_msdos_dir or is_unix_dir or info.filename[-1] == "/"16def resolve_filename(17    destination: pathlib.Path, name: str18) -> typ.Optional[pathlib.Path]:19    target = (destination / name).resolve(strict=False)20    if (21        len(target.parts) <= len(destination.parts)22        or target.parts[: len(destination.parts)] != destination.parts23    ):24        return None25    return target26def extract_zip_file(27    file_data: bytes,28    destination: pathlib.Path,29    root: str,30    progress: typ.Optional[str] = None,31) -> typ.Optional[int]:32    latest_mtime = None33    with ExitStack() as stack:34        file = stack.enter_context(zipfile.ZipFile(BytesIO(file_data), "r"))35        infos: typ.Iterable[zipfile.ZipInfo] = file.infolist()36        if progress:37            infos = stack.enter_context(progressbar(infos, label=progress))38        for item in infos:39            _, root_chk, dest_filename = item.filename.partition(root)40            if root_chk != root:41                continue42            elif not dest_filename:43                destination.mkdir(parents=True, exist_ok=True)44                continue45            dest = resolve_filename(destination, dest_filename)46            if not dest:47                logger.warning(48                    f"Skipping potentially dangeous item {item.filename!r}, "49                    f"it was to be placed at {dest_filename!r}"50                )51                continue52            if is_zipinfo_dir(item):53                dest.mkdir(parents=True, exist_ok=True)54            else:55                mtime = int(datetime(*item.date_time, microsecond=0).timestamp())56                if latest_mtime is None:57                    latest_mtime = mtime58                else:59                    latest_mtime = max(latest_mtime, mtime)...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!!
