Best Python code snippet using autotest_python
mock.py
Source:mock.py  
...950    except AttributeError:951        keys = list(in_dict)952        for key in keys:953            del in_dict[key]954def _patch_stopall():955    for patch in list(_patch._active_patches):956        patch.stop()957patch.object = _patch_object958patch.dict = _patch_dict959patch.multiple = _patch_multiple960patch.stopall = _patch_stopall961patch.TEST_PREFIX = 'test'962magic_methods = 'lt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod neg pos abs invert complex int float index trunc floor ceil '963numerics = 'add sub mul div floordiv mod lshift rshift and xor or pow '964inplace = ' '.join(('i%s' % n for n in numerics.split()))965right = ' '.join(('r%s' % n for n in numerics.split()))966extra = ''967if inPy3k:968    extra = 'bool next '...test_vmu.py
Source:test_vmu.py  
1#!/usr/bin/env python2# python -m unittest -v test_vmu[.TestClass][.test_function]3#pylint: disable=C03014#pylint: disable=R09045import copy6import mock7import os8import sys9import unittest10PATHNAME = os.path.realpath('../')11sys.path.insert(0, PATHNAME)12import vmu13def results_msg(expected, actual, msg):14    divider = '='*70 + '\n'15    return '%s\n' % msg + divider + \16        'EXPECTED:\n%s\n' % str(expected) + divider + \17        'ACTUAL:\n%s\n' % str(actual)18class TestVmu(unittest.TestCase):19    def assertEqualWithResults(self, expected, actual, msg=None):20        """Assert equality with pre-built failure message"""21        self.assertEqual(expected, actual, results_msg(expected, actual, msg))22    def assertNotEqualWithResults(self, expected, actual, msg=None):23        """Assert inequality with pre-built failure message"""24        self.assertNotEqual(expected, actual, results_msg(expected, actual, msg))25class TestPackageSet(TestVmu):26    def test_missing_label(self):27        self.assertRaises(vmu.ParamError, vmu.PackageSet, '', [1, 2, 3])28    def test_empty_packages(self):29        self.assertRaises(vmu.ParamError, vmu.PackageSet, 'foo', [])30    def test_equality(self):31        self.assertEqualWithResults(vmu.PackageSet('foo', [1, 2, 3], True, False),32                                    vmu.PackageSet('foo', [1, 2, 3], True, False),33                                    'PackageSet label or packages equality broken')34        self.assertEqualWithResults(vmu.PackageSet('foo', [1, 2, 3], True, False),35                                    vmu.PackageSet('foo', [1, 2, 3], False, False),36                                    'PackageSet SELinux equality broken')37        # Test mismatched tags38        self.assertRaises(vmu.ParamError, vmu.PackageSet.__eq__,39                          vmu.PackageSet('foo', [1, 2, 3], True, False),40                          vmu.PackageSet('bar', [1, 2, 3], False, False))41        self.assertRaises(vmu.ParamError, vmu.PackageSet.__eq__,42                          vmu.PackageSet('foo', [1, 2, 3], True, False),43                          vmu.PackageSet('foo', [4, 5, 6], False, False))44    def test_inequality(self):45        self.assertNotEqualWithResults(vmu.PackageSet('foo', [1, 2, 3]),46                                       vmu.PackageSet('bar', [4, 5, 6]),47                                       'PackageSet packages inequality broken')48        # Test mismatched tags49        self.assertRaises(vmu.ParamError, vmu.PackageSet.__ne__,50                          vmu.PackageSet('foo', [1, 2, 3], True, False),51                          vmu.PackageSet('bar', [1, 2, 3], False, False))52        self.assertRaises(vmu.ParamError, vmu.PackageSet.__ne__,53                          vmu.PackageSet('foo', [1, 2, 3], True, False),54                          vmu.PackageSet('foo', [4, 5, 6], False, False))55    def test_sorting(self):56        unsorted_pkgs = [vmu.PackageSet('All + GRAM', [1]),57                         vmu.PackageSet('GridFTP', [1]),58                         vmu.PackageSet('VOMS', [1]),59                         vmu.PackageSet('All + GRAM (3.2)', [1]),60                         vmu.PackageSet('All', [1]),61                         vmu.PackageSet('HTCondor', [1]),62                         vmu.PackageSet('GUMS', [1]),63                         vmu.PackageSet('BeStMan', [1]),64                         vmu.PackageSet('foo', [1])]65        unsorted_pkgs.sort()66        self.assertEqualWithResults(vmu.PackageSet.LABEL_ORDER + ['foo'],67                                    [x.label for x in unsorted_pkgs],68                                    'Unexpected sort order')69    def test_defaults(self):70        pkg_set = vmu.PackageSet('foo', [1, 2, 3])71        self.assertEqual(pkg_set.selinux, vmu.PackageSet.SELINUX_DEFAULT, 'Failed to set SELinux default')72        self.assertEqual(pkg_set.java, vmu.PackageSet.OSG_JAVA_DEFAULT, 'Failed to set OSG Java default')73        self.assertEqual(pkg_set.rng, vmu.PackageSet.RNG_DEFAULT, 'Failed to set RNG default')74    def test_hashable(self):75        selinux_enabled = vmu.PackageSet('foo', [1, 2, 3], True, True)76        selinux_disabled = vmu.PackageSet('foo', [1, 2, 3], False, True)77        different_packages = vmu.PackageSet('bar', [4, 5, 6], True, True)78        self.assert_(set([selinux_enabled]),79                     'PackageSet.__hash__() broken')80        self.assertEqual(selinux_enabled.__hash__(),81                         selinux_disabled.__hash__(),82                         'PackageSet hash equality, SELinux agnostic')83        self.assertNotEqual(selinux_enabled.__hash__(), different_packages.__hash__(), 'PackageSet hash inequality')84    def test_from_dict(self):85        pkg_set_dict = {'label': 'gums', 'packages': ['osg-gums', 'rsv'], 'selinux': False, 'osg_java': True, 'rng': True}86        self.assertEqualWithResults(vmu.PackageSet.from_dict(pkg_set_dict),87                                    vmu.PackageSet('gums', ['osg-gums', 'rsv'], False, True, True),88                                    'Manually generated PackageSet differs from one generated from a dict')89class TestLoadRunParams(TestVmu):90    param_dir = '../parameters.d'91    def missing_param_section(self, section):92        patch_glob = mock.patch('vmu.glob')93        mock_glob = patch_glob.start()94        mock_glob.return_value = [1]95        params = {'platforms': ['foo'], 'sources': ['bar'], 'package_sets': [{'label': 'foo', 'packages': [1, 2, 3]}]}96        params.pop(section, None)97        patch_yaml_load = mock.patch('vmu.yaml.load')98        mock_yaml_load = patch_yaml_load.start()99        mock_yaml_load.return_value = params100        self.addCleanup(mock._patch_stopall)101        with mock.patch('__builtin__.open', mock.mock_open()):102            self.assertRaises(vmu.ParamError, vmu.load_run_params, self.param_dir)103    @mock.patch('vmu.glob')104    def test_no_yaml(self, mock_glob):105        mock_glob.return_value = []106        self.assertRaises(vmu.ParamError, vmu.load_run_params, self.param_dir)107    def test_no_platforms_section(self):108        self.missing_param_section('platforms')109    def test_no_sources_section(self):110        self.missing_param_section('sources')111    def test_no_package_sets_section(self):112        self.missing_param_section('package_sets')113    def test_actual_param_dir(self):114        params = vmu.load_run_params('../parameters.d')115        self.assert_(params, 'Failed to read parameters.d')116        for param_set in params:117            for pkg_set in param_set['package_sets']:118                self.assert_(isinstance(pkg_set, vmu.PackageSet),119                             'Did not convert package_set dicts into PackageSet objects')120class TestFlattenParams(TestVmu):121    def test_single_file(self):122        run_params = [123            {'platforms': ['foo'],124             'sources': ['bar', 'foo'],125             'package_sets':126             [127                 vmu.PackageSet('foo', ['foo', 'bar'])128             ]129            }130        ]131        self.assertEqualWithResults(run_params[0], vmu.flatten_run_params(run_params),132                                    'Unexpectedly modified single yaml file')133    def test_mismatched_tags(self):134        pkgs = ['foo', 'bar']135        run_params = [136            {'package_sets':137             [138                 vmu.PackageSet('foo', pkgs),139                 vmu.PackageSet('bar', pkgs),140             ]141            }142        ]143        self.assertRaises(vmu.ParamError, vmu.flatten_run_params, run_params)144    def test_multi_file_single_param(self):145        list1 = ['foo', 'bar']146        list2 = ['baz']147        run_params = [148            {'platforms': list1},149            {'platforms': list1},150            {'platforms': list2},151        ]152        expected = list1 + list2153        self.assertEqualWithResults(expected, vmu.flatten_run_params(run_params)['platforms'],154                                    "Failed to combine multiple files with single 'platforms' section sections")155    def test_multi_file_multi_param(self):156        run_params = [157            {'platforms': ['foo'],158             'sources': ['foo', 'bar'],159             'package_sets':160             [161                 vmu.PackageSet('foo', ['foo', 'bar'])162             ]163            },164            {'platforms': ['foo'],165             'sources': ['foo', 'bar'],166             'package_sets':167             [168                 vmu.PackageSet('foo', ['foo', 'bar'])169             ]170            }171        ]172        expected = copy.deepcopy(run_params).pop()173        self.assertEqualWithResults(expected, vmu.flatten_run_params(run_params),174                                    'Failed to flatten identical files')175    def test_multi_file_multi_pkg_sets(self):176        set1 = [vmu.PackageSet('All', ['osg-tested-internal']),177                vmu.PackageSet('GridFTP', ['osg-gridftp'])]178        set2 = set1 + [vmu.PackageSet('GUMS', ['osg-gums'])]179        run_params = [{'package_sets': set1},180                      {'package_sets': set2}]181        self.assertEqualWithResults(set2, vmu.flatten_run_params(run_params)['package_sets'],182                                    'Failed to combine multiple files with unique package sets')183class TestPackageMapping(TestVmu):184    foo_pkg_set = ['foo']185    bar_pkg_set = ['bar', 'baz']186    flat_params = {187        'package_sets':188        [189            vmu.PackageSet('foo', foo_pkg_set, java=False),190            vmu.PackageSet('bar', bar_pkg_set, java=False)191        ]192    }193    def test_mapping(self):194        expected = {', '.join(self.foo_pkg_set): 'foo', ', '.join(self.bar_pkg_set): 'bar'}195        self.assertEqualWithResults(expected, vmu.package_mapping(self.flat_params),196                                    'Bad mapping for simple case with single package set')197if __name__ == "__main__":...start_stop_implementation.py
Source:start_stop_implementation.py  
...8    def stop(self):9        """Stop an active patch."""10        self._active_patches.discard(self)11        return self.__exit__()12def _patch_stopall():13    """Stop all active patches."""14    for patch in list(_patch._active_patches):15        patch.stop()16def patch(...):17    pass...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!!
