예제 #1
0
class TestSubprocess(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()

    def test_patch_container(self):
        _subprocess.patch()
        self.assertTrue(hasattr(subprocess, '_check_output'))

    def test_unpatch_container(self):
        _subprocess.unpatch()
        self.assertFalse(hasattr(subprocess, '_check_output'))

    def test_check_output_no_container_patched(self):
        self.env.unset('CONTAINER_ID')
        _subprocess.patch()
        subprocess._check_output = Mock()
        subprocess.check_output = Mock()
        _subprocess.check_output(['ls', '/tmp'])
        subprocess._check_output.assert_called_with(['ls', '/tmp'])
        subprocess.check_output.assert_not_called()

    def test_check_output_no_container_not_patched(self):
        self.env.unset('CONTAINER_ID')
        _subprocess.unpatch()
        subprocess.check_output = Mock()
        _subprocess.check_output(['ls', '/tmp'])
        subprocess.check_output.assert_called_with(['ls', '/tmp'])
예제 #2
0
    def setUp(self):
        def getLogger(name):
            self.mock_logger = mock.Mock()
            return self.mock_logger

        sys.modules['logging'].getLogger = getLogger

        def get(url, headers):
            get_return = mock.Mock()
            get_return.ok = True
            get_return.json = mock.Mock()
            get_return.json.return_value = {
                'data': {
                    'status': 1,
                    'default_value': 0.5
                }
            }
            return get_return

        sys.modules['requests'].get = get

        self.env = EnvironmentVarGuard()
        self.env.set('CACHET_TOKEN', 'token2')

        self.configuration = Configuration('config.yml')
        sys.modules['requests'].Timeout = Timeout
        sys.modules['requests'].ConnectionError = ConnectionError
        sys.modules['requests'].HTTPError = HTTPError
예제 #3
0
class TestClient(TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()

    def test_init_default_url(self):
        client = Client()

        self.assertEqual(client.api_root, 'http://localhost:8000/')

    def test_init_custom_url(self):
        client = Client(url='http://testing.com:1234')

        self.assertEqual(client.api_root, 'http://testing.com:1234')

    def test_init_no_login(self):
        client = Client()

        self.assertNotIn('Authorization', client.headers)
        self.assertIsNone(client.auth)

    def test_init_basic_auth(self):
        client = Client()

        client.login('someuser', 'withpass')

        self.assertNotIn('Authorization', client.headers)
        self.assertTrue(client.auth)

    def test_init_token(self):
        client = Client()
        PSEUDO_TOKEN = '123123'

        client.login(token=PSEUDO_TOKEN)

        self.assertTrue(client.headers['Authorization'],
                        'Token {}'.format(PSEUDO_TOKEN))
        self.assertIsNone(client.auth)

    def test_init_no_ssl(self):
        client = Client(check_certificates=False)

        self.assertFalse(client.session.verify)

    # 1.12
    def test_client_raises_error_with_false_url(self):
        with self.assertRaises(ClientError):
            Client(url='wrongurl')

    def test_client_from_env(self):
        """
        Test if the client does not provide a warning when no env file can be found

            Userwarning: 'Could not any envfile.'
            '.../lib/python3.5/site-packages/envparse.py'
        """
        self.env.set('KECHAIN_URL', 'http://localhost:8000')
        with self.env:
            with warnings.catch_warnings(record=True) as captured_warnings:
                client = Client.from_env()
                self.assertEqual(len(captured_warnings), 0)
예제 #4
0
class CaptchaTestingModeMixin(TestCase):
    """Allow Captcha to pass regardless of the value provided"""
    def setUp(self):
        self.captcha_testing_mode_env = EnvironmentVarGuard()
        self.captcha_testing_mode_env.set('RECAPTCHA_TESTING', 'True')

        self.captcha_form_data = {'recaptcha_response_field': 'PASSED'}
예제 #5
0
 def setUp(self):
     self.env = EnvironmentVarGuard()
     value = (
         r"["
         r"(r'^/([a])/([0-9a-f]+)-(zoom)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/650x650/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(zoom)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/650x650/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(raw)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/360x360/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(raw)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/360x360/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(cart)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/83x83/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(cart)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/83x83/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(catalog)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/180x180/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(catalog)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/180x180/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(gallery)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/22x22/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(gallery)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/22x22/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(list)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/63x63/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(list)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/63x63/raw/\2.\4'),"
         r"(r'^/([a])/([0-9a-f]+)-(related)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/47x47/sample/\2.\4'),"
         r"(r'^/([b])/([0-9a-f]+)-(related)\.([a-zA-Z0-9]+)$',"
         r"r'/fit-in/47x47/raw/\2.\4')"
         "]"
     )
     self.env.set('REWRITE_PATTERNS', value)
예제 #6
0
 def setUp(self):
     ''' Ensure that environment variables that are needed to run
         the tests are set
     '''
     self.env = EnvironmentVarGuard()
     # Set MODELICALIBRARY which is required to run
     # runSimulationTranslated.py
     self.env.setdefault("MODELICALIBRARY", "/usr/local/Modelica/Library")
예제 #7
0
def given_client(config=None):
    env = EnvironmentVarGuard()
    return payments(
        add_defaults(
            config, {
                'goid': env.get('goid'),
                'clientId': env.get('clientId'),
                'clientSecret': env.get('clientSecret'),
                'isProductionMode': False
            }), {'logger': debug_logger})
예제 #8
0
파일: tests.py 프로젝트: patogit/alterchef
 def setUp(self):
     self.user = User.objects.create_user("ninja", "*****@*****.**", "password")
     self.network = Network.objects.create(name="quintanalibre.org.ar",
                                           user=self.user)
     self.profile = FwProfile.objects.create(network=self.network)
     self.client.login(username="******", password="******")
     self.cook_url = reverse('cook', kwargs={'slug': self.profile.slug})
     self.job_data = {"devices": ["TLMR3220"], "revision": "stable"}
     self.env = EnvironmentVarGuard()
     self.env.set('LANG', '')
예제 #9
0
def given_client(config=None):
    env = EnvironmentVarGuard()
    return payments(
        add_defaults(config, {
            'goid': env.get('goid'),
            'clientId': env.get('clientId'),
            'clientSecret': env.get('clientSecret'),
            'isProductionMode': False
        }),
        {
            'logger': debug_logger
        }
    )
    def test_environment_api_key_not_set_error(self):
        def real_func():
            self.fail()

        env = EnvironmentVarGuard()
        env.unset('CLOUDFLARE_API_KEY')
        with env:
            try:
                bulk_dns.configured(real_func)()
                self.fail()
            except ValueError as e:
                self.assertTrue('CLOUDFLARE_API_KEY' in e.message)
            except:
                self.fail()
예제 #11
0
class TwilioTest(TestCase):
    def setUp(self):
        test_accout_sid = os.environ.get('TEST_TWILIO_SID')
        test_auth_token = os.environ.get('TEST_TWILIO_AUTH')
        test_to_phone = os.environ.get('TEST_TWILIO_TO_PHONE')
        twilio_test_from_number = '+15005550006'

        self.env = EnvironmentVarGuard()
        self.env.set('KITCAT_TWILIO_SID', test_accout_sid)
        self.env.set('KITACT_TWILIO_AUTH', test_auth_token)
        self.env.set('KITCAT_TWILIO_TO_PHONE', test_to_phone)
        self.env.set('KITCAT_TWILIO_FROM_PHONE', twilio_test_from_number)

    def test_send_sms(self):
        with self.env:
            account_sid = os.environ.get('KITCAT_TWILIO_SID')
            auth_token = os.environ.get('KITACT_TWILIO_AUTH')
            to_phone = os.environ.get('KITCAT_TWILIO_TO_PHONE')
            from_phone = os.environ.get('KITCAT_TWILIO_FROM_PHONE')
            twilio = Twilio(account_sid, auth_token, from_phone)
            test_message = 'Call yo momma!'
            sms = twilio.send_sms(to_phone, test_message)
            assert sms.sid is not None
            assert sms.error_code is None
            assert sms.error_message is None
예제 #12
0
    def test_handler(self, snapshot_instances_mock, prune_snapshots_mock):
        """
        Tests that the handler honors the value of RENTENTION_DAYS and calls
        the snapshot and prune functions with the expected values.
        """
        lightsail = Mock()
        self.env = EnvironmentVarGuard()
        self.env.set('RETENTION_DAYS', '90')

        with patch('boto3.client', return_value=lightsail) as client_factory:
            with self.env:
                index.handler(Mock(), Mock())

        client_factory.assert_called_with('lightsail')
        snapshot_instances_mock.assert_called_with(lightsail)
        prune_snapshots_mock.assert_called_with(lightsail, timedelta(days=90))
예제 #13
0
    def setUp(self):
        ''' Ensure that environment variables that are needed to run
            the tests are set
        '''
        # Set MODELICALIBRARY which is required to run
        # runSimulationTranslated.py
        from git import Repo
        import tempfile
        import os
        import shutil

        self.env = EnvironmentVarGuard()

        self._temDir = tempfile.mkdtemp(prefix='tmp-BuildingsPy-Modelica-Lib-')

        if not os.path.exists(os.path.join(os.getcwd(), "tmp")):
            clo_dir = os.path.join(os.getcwd(), "tmp")
            if os.path.exists(clo_dir):
                shutil.rmtree(clo_dir)
            Repo.clone_from(
                "https://github.com/lbl-srg/modelica-buildings.git",
                clo_dir,
                depth=1)

            if os.path.exists(os.path.join(os.getcwd(), "Buildings")):
                shutil.rmtree(os.path.join(os.getcwd(), "Buildings"))
            shutil.move(os.path.join(os.getcwd(), "tmp", "Buildings"),
                        os.path.join(os.getcwd()))
예제 #14
0
    def setUp(self):
        """ Ensure that environment variables that are needed to run
            the tests are set
        """
        from git import Repo
        import tempfile
        import os
        import shutil

        self.env = EnvironmentVarGuard()

        self._temDir = tempfile.mkdtemp(prefix='tmp-BuildingsPy-Modelica-Lib-')
        self._buiDir = os.path.join(os.getcwd(), "Buildings")

        clo_dir = os.path.join(os.getcwd(), "tmp")

        if os.path.exists(clo_dir):
            shutil.rmtree(clo_dir)

        Repo.clone_from("https://github.com/lbl-srg/modelica-buildings.git",
                        clo_dir,
                        depth=1)

        if os.path.exists(os.path.join(os.getcwd(), "Buildings")):
            shutil.rmtree(os.path.join(os.getcwd(), "Buildings"))
        shutil.move(os.path.join(os.getcwd(), "tmp", "Buildings"),
                    self._buiDir)
        shutil.rmtree(clo_dir)
예제 #15
0
 def setUp(self):
     super(TestEnvironmentProjectKeychain, self).setUp()
     self.env = EnvironmentVarGuard()
     self._clean_env(self.env)
     self.env.set('{}test'.format(self.keychain_class.org_var_prefix),
                  json.dumps(self.org_config.config))
     self.env.set(self.keychain_class.app_var,
                  json.dumps(self.connected_app_config.config))
     self.env.set('{}github'.format(self.keychain_class.service_var_prefix),
                  json.dumps(self.services['github'].config))
     self.env.set(
         '{}mrbelvedere'.format(self.keychain_class.service_var_prefix),
         json.dumps(self.services['mrbelvedere'].config))
     self.env.set(
         '{}apextestsdb'.format(self.keychain_class.service_var_prefix),
         json.dumps(self.services['apextestsdb'].config))
예제 #16
0
 def setUp(self):
     self.env = EnvironmentVarGuard()
     self.env.set('STATUS_ENDPOINT', 'http://localhost/status_nginx')
     self.env.set('SLEEP_DURATION', '60')
     self.env.set('MAX_IDLE_COUNT', '5')
     global count
     count = 0
예제 #17
0
class match_patterns_test_case(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()
        value = (
            r"["
            r"(r'^/([a])/([0-9a-f]+)-(zoom)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/650x650/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(zoom)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/650x650/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(raw)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/360x360/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(raw)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/360x360/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(cart)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/83x83/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(cart)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/83x83/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(catalog)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/180x180/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(catalog)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/180x180/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(gallery)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/22x22/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(gallery)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/22x22/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(list)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/63x63/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(list)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/63x63/raw/\2.\4'),"
            r"(r'^/([a])/([0-9a-f]+)-(related)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/47x47/sample/\2.\4'),"
            r"(r'^/([b])/([0-9a-f]+)-(related)\.([a-zA-Z0-9]+)$',"
            r"r'/fit-in/47x47/raw/\2.\4')"
            "]"
        )
        self.env.set('REWRITE_PATTERNS', value)

    def test_is_five_prime(self):
        with self.env:
            expected = (
                r"/fit-in/650x650/raw"
                r"/4fff89be6cca5cf00afe8062a54796fa.jpg"
                )
            self.assertEqual(
                match_patterns("/b/4fff89be6cca5cf00afe8062a54796fa-zoom.jpg"),
                expected
            )
예제 #18
0
 def test_get_org_not_found(self):
     with EnvironmentVarGuard() as env:
         self._clean_env(env)
         env.set(
             self.keychain_class.app_var,
             json.dumps(self.connected_app_config.config)
         )
         self._test_get_org_not_found()
예제 #19
0
    def test_hpe_config_file_var(self):

        from hpecp.cli.base import get_config_file

        dummy_filepath = "/not/a/real/dir/not_a_real_file"

        env = EnvironmentVarGuard()
        env.set("HPECP_CONFIG_FILE", dummy_filepath)

        with env:
            sys.path.insert(0, os.path.abspath("../../"))
            from bin import cli

            # reload cli module with mock env
            reload(cli)

            self.assertEqual(dummy_filepath, get_config_file())
예제 #20
0
 def setUp(self):
     ''' Ensure that environment variables that are needed to run
         the tests are set
     '''
     self.env = EnvironmentVarGuard()
     # Set MODELICALIBRARY which is required to run
     # runSimulationTranslated.py
     self.env.setdefault("MODELICALIBRARY", "/usr/local/Modelica/Library")
예제 #21
0
 def setUp(self):
     self.user = User.objects.create_user("ninja", "*****@*****.**", "password")
     self.network = Network.objects.create(name="quintanalibre.org.ar", user=self.user)
     self.profile = FwProfile.objects.create(network=self.network)
     self.client.login(username="******", password="******")
     self.cook_url = reverse('cook', kwargs={'slug': self.profile.slug})
     self.job_data = {"devices": ["TLMR3220"], "revision": "stable"}
     self.env = EnvironmentVarGuard()
     self.env.set('LANG', '')
예제 #22
0
 def test_get_default_org(self):
     with EnvironmentVarGuard() as env:
         self._clean_env(env)
         org_config = self.org_config.config.copy()
         org_config['default'] = True
         self.env.set('{}test'.format(self.keychain_class.org_var_prefix),
                      json.dumps(org_config))
         env.set(self.keychain_class.app_var,
                 json.dumps(self.connected_app_config.config))
         self._test_get_default_org()
예제 #23
0
    def test_osx_explict_ldshared(self):
        def gcv(v):
            return 'gcc-4.2 -bundle -undefined dynamic_lookup ' if v == 'LDSHARED' else 'gcc-4.2'

        sysconfig.get_config_var = gcv
        with EnvironmentVarGuard() as env:
            env['CC'] = 'my_cc'
            env['LDSHARED'] = 'my_ld -bundle -dynamic'
            sysconfig.customize_compiler(self.cc)
        self.assertEqual(self.cc.linker_so[0], 'my_ld')
예제 #24
0
class Test_example_dymola_runSimulation(unittest.TestCase):
    """
       This class contains the unit tests for
       :mod:`buildingspy.examples`.
    """

    def setUp(self):
        ''' Ensure that environment variables that are needed to run
            the tests are set
        '''
        self.env = EnvironmentVarGuard()
        # Set MODELICALIBRARY which is required to run
        # runSimulationTranslated.py
        self.env.setdefault("MODELICALIBRARY", "/usr/local/Modelica/Library")
        
    def test_runSimulation(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/runSimulation`
        function.
        '''
        import buildingspy.examples.dymola.runSimulation as s
        s.main()

    def test_runSimulationTranslated(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/runSimulationTranslated`
        function.
        '''
        import buildingspy.examples.dymola.runSimulationTranslated as s
        s.main()

    def test_plotResult(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/plotResult`
        function.
        '''
        import os
        import buildingspy.examples.dymola.plotResult as s
        s.main()
        # Remove the generated plot files
        os.remove("plot.pdf")
        os.remove("plot.png")
예제 #25
0
class Test_example_dymola_runSimulation(unittest.TestCase):
    """
       This class contains the unit tests for
       :mod:`buildingspy.examples`.
    """

    def setUp(self):
        ''' Ensure that environment variables that are needed to run
            the tests are set
        '''
        self.env = EnvironmentVarGuard()
        # Set MODELICALIBRARY which is required to run
        # runSimulationTranslated.py
        self.env.setdefault("MODELICALIBRARY", "/usr/local/Modelica/Library")
        
    def test_runSimulation(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/runSimulation`
        function.
        '''
        import buildingspy.examples.dymola.runSimulation as s
        s.main()

    def test_runSimulationTranslated(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/runSimulationTranslated`
        function.
        '''
        import buildingspy.examples.dymola.runSimulationTranslated as s
        s.main()

    def test_plotResult(self):
        '''
        Tests the :mod:`buildingspy/examples/dymola/plotResult`
        function.
        '''
        import os
        import buildingspy.examples.dymola.plotResult as s
        s.main()
        # Remove the generated plot files
        os.remove("plot.pdf")
        os.remove("plot.png")
예제 #26
0
    def setUp(self):
        test_accout_sid = os.environ.get('TEST_TWILIO_SID')
        test_auth_token = os.environ.get('TEST_TWILIO_AUTH')
        test_to_phone = os.environ.get('TEST_TWILIO_TO_PHONE')
        twilio_test_from_number = '+15005550006'

        self.env = EnvironmentVarGuard()
        self.env.set('KITCAT_TWILIO_SID', test_accout_sid)
        self.env.set('KITACT_TWILIO_AUTH', test_auth_token)
        self.env.set('KITCAT_TWILIO_TO_PHONE', test_to_phone)
        self.env.set('KITCAT_TWILIO_FROM_PHONE', twilio_test_from_number)
예제 #27
0
    def test_osx_cc_overrides_ldshared(self):
        def gcv(v):
            if v == 'LDSHARED':
                return 'gcc-4.2 -bundle -undefined dynamic_lookup '
            return 'gcc-4.2'

        sysconfig.get_config_var = gcv
        with EnvironmentVarGuard() as env:
            env['CC'] = 'my_cc'
            del env['LDSHARED']
            sysconfig.customize_compiler(self.cc)
        self.assertEqual(self.cc.linker_so[0], 'my_cc')
예제 #28
0
class SettingsTest(TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()

    def test_unset(self):
        with self.env:
            self.env.set('QUARK_ENV', 'dev')
            settings = import_fresh_module('quark.settings')

            self.assertTrue(settings.DEBUG)
            self.assertEqual(settings.DATABASES, DEV_DB)

    def test_production(self):
        with self.env:
            self.env.set('QUARK_ENV', 'production')
            settings = import_fresh_module('quark.settings')

            self.assertFalse(settings.DEBUG)
            self.assertEqual(settings.DATABASES, PROD_DB)

    def test_staging(self):
        with self.env:
            self.env.set('QUARK_ENV', 'staging')
            settings = import_fresh_module('quark.settings')

            self.assertFalse(settings.DEBUG)
            self.assertEqual(settings.DATABASES, STAGING_DB)
예제 #29
0
파일: tests.py 프로젝트: nbailey/quark
class SettingsTest(TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()

    def test_unset(self):
        with self.env:
            self.env.set("QUARK_ENV", "dev")
            settings = import_fresh_module("quark.settings")

            self.assertTrue(settings.DEBUG)
            self.assertEqual(settings.DATABASES, DEV_DB)

    def test_production(self):
        with self.env:
            self.env.set("QUARK_ENV", "production")
            settings = import_fresh_module("quark.settings")

            self.assertFalse(settings.DEBUG)
            self.assertEqual(settings.DATABASES, PROD_DB)

    def test_staging(self):
        with self.env:
            self.env.set("QUARK_ENV", "staging")
            settings = import_fresh_module("quark.settings")

            self.assertFalse(settings.DEBUG)
            self.assertEqual(settings.DATABASES, STAGING_DB)
예제 #30
0
 def test_osx_cc_overrides_ldshared(self):
     # Issue #18080:
     # ensure that setting CC env variable also changes default linker
     def gcv(v):
         if v == 'LDSHARED':
             return 'gcc-4.2 -bundle -undefined dynamic_lookup '
         return 'gcc-4.2'
     sysconfig.get_config_var = gcv
     with EnvironmentVarGuard() as env:
         env['CC'] = 'my_cc'
         del env['LDSHARED']
         sysconfig.customize_compiler(self.cc)
     self.assertEqual(self.cc.linker_so[0], 'my_cc')
예제 #31
0
    def setUp(self):
        # use self.env.set('var', 'value') and with self.env: ... to use custom envvars
        self.env = EnvironmentVarGuard()

        self.client = Client(url=TEST_URL)

        if TEST_TOKEN:
            self.client.login(token=TEST_TOKEN)

        self.recorder = Betamax(session=self.client.session)
        self.recorder.use_cassette(self.cassette_name)
        self.recorder.start()
        self.project = self.client.scope(TEST_SCOPE_NAME)
예제 #32
0
class JWTAuthenticationTestCase(BaseTestCase):
    def setUp(self):
        BaseTestCase.create_schema(self)
        self.client = Client()
        self.env = EnvironmentVarGuard()
        self.env.set('JWT_KEY', 'secret')

    def test_redirection_to_login_for_unauthenticated_requests(self):
        with self.env:
            response = self.client.get('/')
            self.assertEqual(response.status_code, 302)
            self.assertTrue(response.url.startswith('/login'))

    def test_login_with_jwt(self):
        with self.env:
            token = jwt.encode({'username': '******'},
                               'secret',
                               algorithm='HS256')
            response = self.client.get('/' + '/?accessToken=' + token)
            self.assertEqual(response.status_code, 200)

    def tearDown(self):
        BaseTestCase.delete_schema(self)
예제 #33
0
 def test_osx_explict_ldshared(self):
     # Issue #18080:
     # ensure that setting CC env variable does not change
     #   explicit LDSHARED setting for linker
     def gcv(v):
         if v == 'LDSHARED':
             return 'gcc-4.2 -bundle -undefined dynamic_lookup '
         return 'gcc-4.2'
     sysconfig.get_config_var = gcv
     with EnvironmentVarGuard() as env:
         env['CC'] = 'my_cc'
         env['LDSHARED'] = 'my_ld -bundle -dynamic'
         sysconfig.customize_compiler(self.cc)
     self.assertEqual(self.cc.linker_so[0], 'my_ld')
예제 #34
0
    def test_getuserbase(self):
        site.USER_BASE = None
        user_base = site.getuserbase()

        # the call sets site.USER_BASE
        self.assertEqual(site.USER_BASE, user_base)

        # let's set PYTHONUSERBASE and see if it uses it
        site.USER_BASE = None
        import sysconfig
        sysconfig._CONFIG_VARS = None

        with EnvironmentVarGuard() as environ:
            environ['PYTHONUSERBASE'] = 'xoxo'
            self.assertTrue(site.getuserbase().startswith('xoxo'),
                            site.getuserbase())
예제 #35
0
def initialise_database():
    basedir = settings.BASE_DIR

    # path to find the fixture data
    fixture_dir = os.path.join(basedir, 'fixtures/projects/1')

    # set the paths to upload and process the test data
    test_media_root = settings.TEST_MEDIA_ROOT  # + '_test'
    #settings.MEDIA_ROOT = test_media_root

    # for use in the R pipeline
    env = EnvironmentVarGuard()
    #env.set('PIMP_DATABASE_NAME', os.environ['PIMP_TEST_DATABASE_NAME'])
    #env.set('PIMP_DATABASE_FILENAME', '')
    #env.set('PIMP_MEDIA_ROOT', test_media_root)
    return fixture_dir, test_media_root, env
    def test_environment_completely_set_and_real_func_called(self):
        def real_func(cf_lib_wrapper=None):
            self.assertIsNotNone(cf_lib_wrapper)
            self.assertEqual('hello key', cf_lib_wrapper.api_key)
            self.assertEqual('hello email', cf_lib_wrapper.api_email)

        env = EnvironmentVarGuard()
        env.set('CLOUDFLARE_API_KEY', 'hello key')
        env.set('CLOUDFLARE_API_EMAIL', 'hello email')
        with env:
            bulk_dns.configured(real_func)()
예제 #37
0
 def setUp(self):
     super(TestEnvironmentProjectKeychain, self).setUp()
     self.env = EnvironmentVarGuard()
     self._clean_env(self.env)
     self.env.set("{}test".format(self.keychain_class.org_var_prefix), json.dumps(self.org_config.config))
     self.env.set(self.keychain_class.app_var, json.dumps(self.connected_app_config.config))
     self.env.set(
         "{}github".format(self.keychain_class.service_var_prefix), json.dumps(self.services["github"].config)
     )
     self.env.set(
         "{}mrbelvedere".format(self.keychain_class.service_var_prefix),
         json.dumps(self.services["mrbelvedere"].config),
     )
     self.env.set(
         "{}apextestsdb".format(self.keychain_class.service_var_prefix),
         json.dumps(self.services["apextestsdb"].config),
     )
예제 #38
0
class TestDockerHelpers(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()

    def test_is_container_when_container_id(self):
        self.env.set('CONTAINER_ID', CONTAINER_ID)
        self.assertTrue(container.is_container())

    def test_not_container_when_no_container_id(self):
        self.env.unset('CONTAINER_ID')
        self.assertFalse(container.is_container())

    def test_container_id(self):
        self.env.set('CONTAINER_ID', CONTAINER_ID)
        self.assertEqual(CONTAINER_ID, container.get_container_id())

    def test_container_ip(self):
        self.env.set('CONTAINER_IP', CONTAINER_IP)
        self.assertEqual(CONTAINER_IP, container.get_container_ip())
예제 #39
0
    def test_imp_module(self):
        # Verify that the imp module can correctly load and find .py files

        # XXX (ncoghlan): It would be nice to use test_support.CleanImport
        # here, but that breaks because the os module registers some
        # handlers in copy_reg on import. Since CleanImport doesn't
        # revert that registration, the module is left in a broken
        # state after reversion. Reinitialising the module contents
        # and just reverting os.environ to its previous state is an OK
        # workaround
        orig_path = os.path
        orig_getenv = os.getenv
        with EnvironmentVarGuard():
            x = imp.find_module("os")
            new_os = imp.load_module("os", *x)
            self.assertIs(os, new_os)
            self.assertIs(orig_path, new_os.path)
            self.assertIsNot(orig_getenv, new_os.getenv)
    def setUp(self):
        def getLogger(name):
            self.mock_logger = mock.Mock()
            return self.mock_logger

        sys.modules['logging'].getLogger = getLogger

        def get(url, headers):
            get_return = mock.Mock()
            get_return.ok = True
            get_return.json = mock.Mock()
            get_return.json.return_value = {'data': {'status': 1}}
            return get_return

        sys.modules['requests'].get = get

        self.env = EnvironmentVarGuard()
        self.env.set('CACHET_TOKEN', 'token2')

        self.configuration = Configuration('config.yml')
        sys.modules['requests'].Timeout = Timeout
        sys.modules['requests'].ConnectionError = ConnectionError
        sys.modules['requests'].HTTPError = HTTPError
예제 #41
0
class MonitorTest(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()
        self.env.set('STATUS_ENDPOINT', 'http://localhost/status_nginx')
        self.env.set('SLEEP_DURATION', '60')
        self.env.set('MAX_IDLE_COUNT', '5')
        global count
        count = 0

    @mock.patch('requests.get')
    def test(self, mock_requests, mock_time):
        mock_requests.side_effect = get_return
        self.assertTrue(monitor.main())

    @mock.patch('requests.get')
    def test_with_reset(self, mock_requests, mock_time):
        mock_requests.side_effect = get_return_with_reset
        self.assertTrue(monitor.main())
 def setUp(self):
     super(TestPaverBokChoyCmd, self).setUp()
     self.shard = os.environ.get('SHARD')
     self.env_var_override = EnvironmentVarGuard()
예제 #43
0
파일: tests.py 프로젝트: nbailey/quark
 def setUp(self):
     self.env = EnvironmentVarGuard()
예제 #44
0
class TestEnvironmentProjectKeychain(TestBaseProjectKeychain):
    keychain_class = EnvironmentProjectKeychain

    def setUp(self):
        super(TestEnvironmentProjectKeychain, self).setUp()
        self.env = EnvironmentVarGuard()
        self._clean_env(self.env)
        self.env.set("{}test".format(self.keychain_class.org_var_prefix), json.dumps(self.org_config.config))
        self.env.set(self.keychain_class.app_var, json.dumps(self.connected_app_config.config))
        self.env.set(
            "{}github".format(self.keychain_class.service_var_prefix), json.dumps(self.services["github"].config)
        )
        self.env.set(
            "{}mrbelvedere".format(self.keychain_class.service_var_prefix),
            json.dumps(self.services["mrbelvedere"].config),
        )
        self.env.set(
            "{}apextestsdb".format(self.keychain_class.service_var_prefix),
            json.dumps(self.services["apextestsdb"].config),
        )

    def _clean_env(self, env):
        for key, value in env.items():
            if key.startswith(self.keychain_class.org_var_prefix):
                del env[key]
        for key, value in env.items():
            if key.startswith(self.keychain_class.service_var_prefix):
                del env[key]
        if self.keychain_class.app_var in env:
            del env[self.keychain_class.app_var]

    def test_get_org(self):
        keychain = self.keychain_class(self.project_config, self.key)
        self.assertEquals(keychain.orgs.keys(), ["test"])
        self.assertEquals(keychain.get_org("test").config, self.org_config.config)

    def _test_list_orgs(self):
        with self.env:
            keychain = self.keychain_class(self.project_config, self.key)
            self.assertEquals(keychain.list_orgs(), ["test"])

    def test_list_orgs_empty(self):
        with EnvironmentVarGuard() as env:
            self._clean_env(env)
            env.set(self.keychain_class.app_var, json.dumps(self.connected_app_config.config))
            self._test_list_orgs_empty()

    def test_get_org_not_found(self):
        with EnvironmentVarGuard() as env:
            self._clean_env(env)
            env.set(self.keychain_class.app_var, json.dumps(self.connected_app_config.config))
            self._test_get_org_not_found()

    def test_get_default_org(self):
        with EnvironmentVarGuard() as env:
            self._clean_env(env)
            org_config = self.org_config.config.copy()
            org_config["default"] = True
            self.env.set("{}test".format(self.keychain_class.org_var_prefix), json.dumps(org_config))
            env.set(self.keychain_class.app_var, json.dumps(self.connected_app_config.config))
            self._test_get_default_org()
예제 #45
0
class JobsTest(TestCase):

    def setUp(self):
        self.user = User.objects.create_user("ninja", "*****@*****.**", "password")
        self.network = Network.objects.create(name="quintanalibre.org.ar", user=self.user)
        self.profile = FwProfile.objects.create(network=self.network)
        self.client.login(username="******", password="******")
        self.cook_url = reverse('cook', kwargs={'slug': self.profile.slug})
        self.job_data = {"devices": ["TLMR3220"], "revision": "stable"}
        self.env = EnvironmentVarGuard()
        self.env.set('LANG', '')

    def tearDown(self):
        FwJob.set_make_commands_func(FwJob.default_make_commands)

    def test_process_some_jobs(self):
        FwJob.objects.create(profile=self.profile, user=self.user, job_data=self.job_data)
        FwJob.objects.create(profile=self.profile, user=self.user, job_data=self.job_data)

        FwJob.set_make_commands_func(lambda *x: ["sleep 0.1"])

        self.assertEqual(len(FwJob.started.all()), 0)
        self.assertEqual(len(FwJob.waiting.all()), 2)

        FwJob.process_jobs(sync=True)
        self.assertEqual(len(FwJob.waiting.all()), 1)
        self.assertEqual(len(FwJob.finished.all()), 1)

        FwJob.process_jobs(sync=True)
        self.assertEqual(len(FwJob.finished.all()), 2)

    def test_failed_job(self):
        fwjob = FwJob.objects.create(profile=self.profile, user=self.user, job_data=self.job_data)
        FwJob.set_make_commands_func(lambda *x: ["ls /inexistent"])

        FwJob.process_jobs(sync=True)
        self.assertEqual(len(FwJob.failed.all()), 1)
        with self.env:
            fwjob = FwJob.objects.get(pk=fwjob.pk)
            self.assertTrue("No such file or directory" in fwjob.build_log)

    def _test_cook(self):
        response = self.client.get(self.cook_url)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(self.cook_url, {"other_devices": "TLMR3020", "openwrt_revision": "stable"})
        self.assertEqual(response.status_code, 302)

        self.assertEqual(len(FwJob.started.all()), 0)
        self.assertEqual(len(FwJob.waiting.all()), 1)
        FwJob.process_jobs()
        self.assertEqual(len(FwJob.started.all()), 1)
        self.assertEqual(len(FwJob.waiting.all()), 0)

    def test_make_commands(self):
        commands = FwJob.make_commands("quintanalibre.org.ar", "profile1", ["TLMR3220", "NONEatherosDefault"], "33333")
        self.assertTrue("33333 ar71xx quintanalibre.org.ar profile1 TLMR3220" in commands[0])
        self.assertTrue("33333 atheros quintanalibre.org.ar profile1 Default" in commands[1])

    def test_view_jobs(self):
        self.assertContains(self.client.get(reverse("view-jobs")), "List Jobs")

    def test_job_detail(self):
        fwjob = FwJob.objects.create(profile=self.profile, user=self.user, job_data=self.job_data)
        self.assertContains(self.client.get(reverse("fwjob-detail", kwargs={"pk": fwjob.pk})), "WAITING")
        fwjob.status = "FAILED"
        fwjob.build_log = "the log"
        fwjob.save()
        self.assertContains(self.client.get(reverse("fwjob-detail", kwargs={"pk": fwjob.pk})), "the log")
class TestPaverBokChoyCmd(unittest.TestCase):
    """
    Paver Bok Choy Command test cases
    """

    def _expected_command(self, name, store=None, verify_xss=True):
        """
        Returns the command that is expected to be run for the given test spec
        and store.
        """

        shard_str = '/shard_' + self.shard if self.shard else ''

        expected_statement = [
            "DEFAULT_STORE={}".format(store),
            "SCREENSHOT_DIR='{}/test_root/log{}'".format(REPO_DIR, shard_str),
            "BOK_CHOY_HAR_DIR='{}/test_root/log{}/hars'".format(REPO_DIR, shard_str),
            "BOKCHOY_A11Y_CUSTOM_RULES_FILE='{}/{}'".format(
                REPO_DIR,
                'node_modules/edx-custom-a11y-rules/lib/custom_a11y_rules.js'
            ),
            "SELENIUM_DRIVER_LOG_DIR='{}/test_root/log{}'".format(REPO_DIR, shard_str),
            "VERIFY_XSS='{}'".format(verify_xss),
            "python",
            "-Wd",
            "-m",
            "pytest",
            "{}/common/test/acceptance/{}".format(REPO_DIR, name),
            "--junitxml={}/reports/bok_choy{}/xunit.xml".format(REPO_DIR, shard_str),
            "--verbose",
        ]
        return expected_statement

    def setUp(self):
        super(TestPaverBokChoyCmd, self).setUp()
        self.shard = os.environ.get('SHARD')
        self.env_var_override = EnvironmentVarGuard()

    def test_default(self):
        suite = BokChoyTestSuite('')
        name = 'tests'
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_suite_spec(self):
        spec = 'test_foo.py'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_class_spec(self):
        spec = 'test_foo.py:FooTest'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_testcase_spec(self):
        spec = 'test_foo.py:FooTest.test_bar'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_spec_with_draft_default_store(self):
        spec = 'test_foo.py'
        suite = BokChoyTestSuite('', test_spec=spec, default_store='draft')
        name = 'tests/{}'.format(spec)
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=name, store='draft')
        )

    def test_invalid_default_store(self):
        # the cmd will dumbly compose whatever we pass in for the default_store
        suite = BokChoyTestSuite('', default_store='invalid')
        name = 'tests'
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=name, store='invalid')
        )

    def test_serversonly(self):
        suite = BokChoyTestSuite('', serversonly=True)
        self.assertEqual(suite.cmd, None)

    def test_verify_xss(self):
        suite = BokChoyTestSuite('', verify_xss=True)
        name = 'tests'
        self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=True))

    def test_verify_xss_env_var(self):
        self.env_var_override.set('VERIFY_XSS', 'False')
        with self.env_var_override:
            suite = BokChoyTestSuite('')
            name = 'tests'
            self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=False))

    def test_test_dir(self):
        test_dir = 'foo'
        suite = BokChoyTestSuite('', test_dir=test_dir)
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=test_dir)
        )

    def test_verbosity_settings_1_process(self):
        """
        Using 1 process means paver should ask for the traditional xunit plugin for plugin results
        """
        expected_verbosity_command = [
            "--junitxml={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else ''
            ),
            "--verbose",
        ]
        suite = BokChoyTestSuite('', num_processes=1)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)

    def test_verbosity_settings_2_processes(self):
        """
        Using multiple processes means specific xunit, coloring, and process-related settings should
        be used.
        """
        process_count = 2
        expected_verbosity_command = [
            "--junitxml={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else '',
            ),
            u"-n {}".format(process_count),
            "--color=no",
            "--verbose",
        ]
        suite = BokChoyTestSuite('', num_processes=process_count)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)

    def test_verbosity_settings_3_processes(self):
        """
        With the above test, validate that num_processes can be set to various values
        """
        process_count = 3
        expected_verbosity_command = [
            "--junitxml={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else '',
            ),
            u"-n {}".format(process_count),
            "--color=no",
            "--verbose",
        ]
        suite = BokChoyTestSuite('', num_processes=process_count)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)
class TestPaverBokChoyCmd(unittest.TestCase):
    """
    Paver Bok Choy Command test cases
    """

    def _expected_command(self, name, store=None, verify_xss=True):
        """
        Returns the command that is expected to be run for the given test spec
        and store.
        """

        shard_str = "/shard_" + self.shard if self.shard else ""

        expected_statement = [
            "DEFAULT_STORE={}".format(store),
            "SCREENSHOT_DIR='{}/test_root/log{}'".format(REPO_DIR, shard_str),
            "BOK_CHOY_HAR_DIR='{}/test_root/log{}/hars'".format(REPO_DIR, shard_str),
            "BOKCHOY_A11Y_CUSTOM_RULES_FILE='{}/{}'".format(
                REPO_DIR, "node_modules/edx-custom-a11y-rules/lib/custom_a11y_rules.js"
            ),
            "SELENIUM_DRIVER_LOG_DIR='{}/test_root/log{}'".format(REPO_DIR, shard_str),
            "VERIFY_XSS='{}'".format(verify_xss),
            "nosetests",
            "{}/common/test/acceptance/{}".format(REPO_DIR, name),
            "--xunit-file={}/reports/bok_choy{}/xunit.xml".format(REPO_DIR, shard_str),
            "--verbosity=2",
        ]
        return expected_statement

    def setUp(self):
        super(TestPaverBokChoyCmd, self).setUp()
        self.shard = os.environ.get("SHARD")
        self.env_var_override = EnvironmentVarGuard()

    def test_default(self):
        suite = BokChoyTestSuite("")
        name = "tests"
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_suite_spec(self):
        spec = "test_foo.py"
        suite = BokChoyTestSuite("", test_spec=spec)
        name = "tests/{}".format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_class_spec(self):
        spec = "test_foo.py:FooTest"
        suite = BokChoyTestSuite("", test_spec=spec)
        name = "tests/{}".format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_testcase_spec(self):
        spec = "test_foo.py:FooTest.test_bar"
        suite = BokChoyTestSuite("", test_spec=spec)
        name = "tests/{}".format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_spec_with_draft_default_store(self):
        spec = "test_foo.py"
        suite = BokChoyTestSuite("", test_spec=spec, default_store="draft")
        name = "tests/{}".format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name, store="draft"))

    def test_invalid_default_store(self):
        # the cmd will dumbly compose whatever we pass in for the default_store
        suite = BokChoyTestSuite("", default_store="invalid")
        name = "tests"
        self.assertEqual(suite.cmd, self._expected_command(name=name, store="invalid"))

    def test_serversonly(self):
        suite = BokChoyTestSuite("", serversonly=True)
        self.assertEqual(suite.cmd, None)

    def test_verify_xss(self):
        suite = BokChoyTestSuite("", verify_xss=True)
        name = "tests"
        self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=True))

    def test_verify_xss_env_var(self):
        self.env_var_override.set("VERIFY_XSS", "False")
        with self.env_var_override:
            suite = BokChoyTestSuite("")
            name = "tests"
            self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=False))

    def test_test_dir(self):
        test_dir = "foo"
        suite = BokChoyTestSuite("", test_dir=test_dir)
        self.assertEqual(suite.cmd, self._expected_command(name=test_dir))

    def test_verbosity_settings_1_process(self):
        """
        Using 1 process means paver should ask for the traditional xunit plugin for plugin results
        """
        expected_verbosity_command = [
            "--xunit-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR, shard_str="/shard_" + self.shard if self.shard else ""
            ),
            "--verbosity=2",
        ]
        suite = BokChoyTestSuite("", num_processes=1)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)

    def test_verbosity_settings_2_processes(self):
        """
        Using multiple processes means specific xunit, coloring, and process-related settings should
        be used.
        """
        process_count = 2
        expected_verbosity_command = [
            "--xunitmp-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR, shard_str="/shard_" + self.shard if self.shard else ""
            ),
            "--processes={}".format(process_count),
            "--no-color",
            "--process-timeout=1200",
        ]
        suite = BokChoyTestSuite("", num_processes=process_count)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)

    def test_verbosity_settings_3_processes(self):
        """
        With the above test, validate that num_processes can be set to various values
        """
        process_count = 3
        expected_verbosity_command = [
            "--xunitmp-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml".format(
                repo_dir=REPO_DIR, shard_str="/shard_" + self.shard if self.shard else ""
            ),
            "--processes={}".format(process_count),
            "--no-color",
            "--process-timeout=1200",
        ]
        suite = BokChoyTestSuite("", num_processes=process_count)
        self.assertEqual(suite.verbosity_processes_command, expected_verbosity_command)

    def test_invalid_verbosity_and_processes(self):
        """
        If an invalid combination of verbosity and number of processors is passed in, a
        BuildFailure should be raised
        """
        suite = BokChoyTestSuite("", num_processes=2, verbosity=3)
        with self.assertRaises(BuildFailure):
            # pylint: disable=pointless-statement
            suite.verbosity_processes_command
예제 #48
0
파일: test_getopt.py 프로젝트: 89sos98/main
 def setUp(self):
     self.env = EnvironmentVarGuard()
     if "POSIXLY_CORRECT" in self.env:
         del self.env["POSIXLY_CORRECT"]
예제 #49
0
파일: test_getopt.py 프로젝트: 89sos98/main
class GetoptTests(unittest.TestCase):
    def setUp(self):
        self.env = EnvironmentVarGuard()
        if "POSIXLY_CORRECT" in self.env:
            del self.env["POSIXLY_CORRECT"]

    def tearDown(self):
        self.env.__exit__()
        del self.env

    def assertError(self, *args, **kwargs):
        self.assertRaises(getopt.GetoptError, *args, **kwargs)

    def test_short_has_arg(self):
        self.assertTrue(getopt.short_has_arg('a', 'a:'))
        self.assertFalse(getopt.short_has_arg('a', 'a'))
        self.assertError(getopt.short_has_arg, 'a', 'b')

    def test_long_has_args(self):
        has_arg, option = getopt.long_has_args('abc', ['abc='])
        self.assertTrue(has_arg)
        self.assertEqual(option, 'abc')

        has_arg, option = getopt.long_has_args('abc', ['abc'])
        self.assertFalse(has_arg)
        self.assertEqual(option, 'abc')

        has_arg, option = getopt.long_has_args('abc', ['abcd'])
        self.assertFalse(has_arg)
        self.assertEqual(option, 'abcd')

        self.assertError(getopt.long_has_args, 'abc', ['def'])
        self.assertError(getopt.long_has_args, 'abc', [])
        self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde'])

    def test_do_shorts(self):
        opts, args = getopt.do_shorts([], 'a', 'a', [])
        self.assertEqual(opts, [('-a', '')])
        self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a1', 'a:', [])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, [])

        #opts, args = getopt.do_shorts([], 'a=1', 'a:', [])
        #self.assertEqual(opts, [('-a', '1')])
        #self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a', 'a:', ['1'])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2'])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, ['2'])

        self.assertError(getopt.do_shorts, [], 'a1', 'a', [])
        self.assertError(getopt.do_shorts, [], 'a', 'a:', [])

    def test_do_longs(self):
        opts, args = getopt.do_longs([], 'abc', ['abc'], [])
        self.assertEqual(opts, [('--abc', '')])
        self.assertEqual(args, [])

        opts, args = getopt.do_longs([], 'abc=1', ['abc='], [])
        self.assertEqual(opts, [('--abc', '1')])
        self.assertEqual(args, [])

        opts, args = getopt.do_longs([], 'abc=1', ['abcd='], [])
        self.assertEqual(opts, [('--abcd', '1')])
        self.assertEqual(args, [])

        opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], [])
        self.assertEqual(opts, [('--abc', '')])
        self.assertEqual(args, [])

        # Much like the preceding, except with a non-alpha character ("-") in
        # option name that precedes "="; failed in
        # http://python.org/sf/126863
        opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], [])
        self.assertEqual(opts, [('--foo', '42')])
        self.assertEqual(args, [])

        self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], [])
        self.assertError(getopt.do_longs, [], 'abc', ['abc='], [])

    def test_getopt(self):
        # note: the empty string between '-a' and '--beta' is significant:
        # it simulates an empty string option argument ('-a ""') on the
        # command line.
        cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a',
                   '', '--beta', 'arg1', 'arg2']

        opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
        self.assertEqual(opts, [('-a', '1'), ('-b', ''),
                                ('--alpha', '2'), ('--beta', ''),
                                ('-a', '3'), ('-a', ''), ('--beta', '')])
        # Note ambiguity of ('-b', '') and ('-a', '') above. This must be
        # accounted for in the code that calls getopt().
        self.assertEqual(args, ['arg1', 'arg2'])

        self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta'])

    def test_gnu_getopt(self):
        # Test handling of GNU style scanning mode.
        cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']

        # GNU style
        opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
        self.assertEqual(args, ['arg1'])
        self.assertEqual(opts, [('-a', ''), ('-b', '1'),
                                ('--alpha', ''), ('--beta', '2')])

        # recognize "-" as an argument
        opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', [])
        self.assertEqual(args, ['-'])
        self.assertEqual(opts, [('-a', ''), ('-b', '-')])

        # Posix style via +
        opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
        self.assertEqual(opts, [('-a', '')])
        self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])

        # Posix style via POSIXLY_CORRECT
        self.env["POSIXLY_CORRECT"] = "1"
        opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
        self.assertEqual(opts, [('-a', '')])
        self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])

    def test_libref_examples(self):
        s = """
        Examples from the Library Reference:  Doc/lib/libgetopt.tex

        An example using only Unix style options:


        >>> import getopt
        >>> args = '-a -b -cfoo -d bar a1 a2'.split()
        >>> args
        ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'abc:d:')
        >>> optlist
        [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
        >>> args
        ['a1', 'a2']

        Using long option names is equally easy:


        >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
        >>> args = s.split()
        >>> args
        ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'x', [
        ...     'condition=', 'output-file=', 'testing'])
        >>> optlist
        [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
        >>> args
        ['a1', 'a2']
        """

        import types
        m = types.ModuleType("libreftest", s)
        run_doctest(m, verbose)
예제 #50
0
def AWSEnvironmentVarGuard():
    env = EnvironmentVarGuard()
    env.unset('AWS_ACCESS_KEY_ID')
    env.unset('AWS_ACCESS_KEY')
    env.unset('AWS_SECRET_ACCESS_KEY')
    env.unset('AWS_SECRET')
    env.unset('AWS_DEFAULT_REGION')
    env.set('BODYLABS_CREDENTIAL_FILE', '/this_file_does_not_exist')
    env.set('AWS_CONFIG_FILE', '/this_file_does_not_exist')
    env.set('AWS_CREDENTIAL_FILE', '/this_file_does_not_exist')
    return env
class ConfigurationTest(unittest.TestCase):
    def setUp(self):
        def getLogger(name):
            self.mock_logger = mock.Mock()
            return self.mock_logger

        sys.modules['logging'].getLogger = getLogger

        def get(url, headers):
            get_return = mock.Mock()
            get_return.ok = True
            get_return.json = mock.Mock()
            get_return.json.return_value = {'data': {'status': 1}}
            return get_return

        sys.modules['requests'].get = get

        self.env = EnvironmentVarGuard()
        self.env.set('CACHET_TOKEN', 'token2')

        self.configuration = Configuration('config.yml')
        sys.modules['requests'].Timeout = Timeout
        sys.modules['requests'].ConnectionError = ConnectionError
        sys.modules['requests'].HTTPError = HTTPError

    def test_init(self):
        self.assertEqual(len(self.configuration.data), 3, 'Configuration data size is incorrect')
        self.assertEquals(len(self.configuration.expectations), 3, 'Number of expectations read from file is incorrect')
        self.assertDictEqual(self.configuration.headers, {'X-Cachet-Token': 'token2'}, 'Header was not set correctly')
        self.assertEquals(self.configuration.api_url, 'https://demo.cachethq.io/api/v1',
                          'Cachet API URL was set incorrectly')

    def test_evaluate(self):
        def total_seconds():
            return 0.1

        def request(method, url, timeout=None):
            response = mock.Mock()
            response.status_code = 200
            response.elapsed = mock.Mock()
            response.elapsed.total_seconds = total_seconds
            response.text = '<body>'
            return response

        sys.modules['requests'].request = request
        self.configuration.evaluate()

        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_OPERATIONAL,
                          'Component status set incorrectly')

    def test_evaluate_with_failure(self):
        def total_seconds():
            return 0.1

        def request(method, url, timeout=None):
            response = mock.Mock()
            # We are expecting a 200 response, so this will fail the expectation.
            response.status_code = 400
            response.elapsed = mock.Mock()
            response.elapsed.total_seconds = total_seconds
            response.text = '<body>'
            return response

        sys.modules['requests'].request = request
        self.configuration.evaluate()

        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_PARTIAL_OUTAGE,
                          'Component status set incorrectly')

    def test_evaluate_with_timeout(self):
        def request(method, url, timeout=None):
            self.assertEquals(method, 'GET', 'Incorrect HTTP method')
            self.assertEquals(url, 'http://localhost:8080/swagger', 'Monitored URL is incorrect')
            self.assertEquals(timeout, 0.010)

            raise Timeout()

        sys.modules['requests'].request = request
        self.configuration.evaluate()

        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_PERFORMANCE_ISSUES,
                          'Component status set incorrectly')
        self.mock_logger.warning.assert_called_with('Request timed out')

    def test_evaluate_with_connection_error(self):
        def request(method, url, timeout=None):
            self.assertEquals(method, 'GET', 'Incorrect HTTP method')
            self.assertEquals(url, 'http://localhost:8080/swagger', 'Monitored URL is incorrect')
            self.assertEquals(timeout, 0.010)

            raise ConnectionError()

        sys.modules['requests'].request = request
        self.configuration.evaluate()

        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_PARTIAL_OUTAGE,
                          'Component status set incorrectly')
        self.mock_logger.warning.assert_called_with('The URL is unreachable: GET http://localhost:8080/swagger')

    def test_evaluate_with_http_error(self):
        def request(method, url, timeout=None):
            self.assertEquals(method, 'GET', 'Incorrect HTTP method')
            self.assertEquals(url, 'http://localhost:8080/swagger', 'Monitored URL is incorrect')
            self.assertEquals(timeout, 0.010)

            raise HTTPError()

        sys.modules['requests'].request = request
        self.configuration.evaluate()

        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_PARTIAL_OUTAGE,
                          'Component status set incorrectly')
        self.mock_logger.exception.assert_called_with('Unexpected HTTP response')

    def test_push_status(self):
        def put(url, params=None, headers=None):
            self.assertEquals(url, 'https://demo.cachethq.io/api/v1/components/1', 'Incorrect cachet API URL')
            self.assertDictEqual(params, {'id': 1, 'status': 1}, 'Incorrect component update parameters')
            self.assertDictEqual(headers, {'X-Cachet-Token': 'token2'}, 'Incorrect component update parameters')

            response = mock.Mock()
            response.status_code = 200
            return response

        sys.modules['requests'].put = put
        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_OPERATIONAL,
                          'Incorrect component update parameters')
        self.configuration.push_status()

    def test_push_status_with_failure(self):
        def put(url, params=None, headers=None):
            self.assertEquals(url, 'https://demo.cachethq.io/api/v1/components/1', 'Incorrect cachet API URL')
            self.assertDictEqual(params, {'id': 1, 'status': 1}, 'Incorrect component update parameters')
            self.assertDictEqual(headers, {'X-Cachet-Token': 'token2'}, 'Incorrect component update parameters')

            response = mock.Mock()
            response.status_code = 400
            return response

        sys.modules['requests'].put = put
        self.assertEquals(self.configuration.status, cachet_url_monitor.status.COMPONENT_STATUS_OPERATIONAL,
                          'Incorrect component update parameters')
        self.configuration.push_status()
class TestPaverBokChoyCmd(unittest.TestCase):
    """
    Paver Bok Choy Command test cases
    """

    def _expected_command(self, name, store=None, verify_xss=True):
        """
        Returns the command that is expected to be run for the given test spec
        and store.
        """

        expected_statement = (
            "DEFAULT_STORE={default_store} "
            "SCREENSHOT_DIR='{repo_dir}/test_root/log{shard_str}' "
            "BOK_CHOY_HAR_DIR='{repo_dir}/test_root/log{shard_str}/hars' "
            "BOKCHOY_A11Y_CUSTOM_RULES_FILE='{repo_dir}/{a11y_custom_file}' "
            "SELENIUM_DRIVER_LOG_DIR='{repo_dir}/test_root/log{shard_str}' "
            "VERIFY_XSS='{verify_xss}' "
            "nosetests {repo_dir}/common/test/acceptance/{exp_text} "
            "--with-xunit "
            "--xunit-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml "
            "--verbosity=2 "
        ).format(
            default_store=store,
            repo_dir=REPO_DIR,
            shard_str='/shard_' + self.shard if self.shard else '',
            exp_text=name,
            a11y_custom_file='node_modules/edx-custom-a11y-rules/lib/custom_a11y_rules.js',
            verify_xss=verify_xss
        )
        return expected_statement

    def setUp(self):
        super(TestPaverBokChoyCmd, self).setUp()
        self.shard = os.environ.get('SHARD')
        self.env_var_override = EnvironmentVarGuard()

    def test_default(self):
        suite = BokChoyTestSuite('')
        name = 'tests'
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_suite_spec(self):
        spec = 'test_foo.py'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_class_spec(self):
        spec = 'test_foo.py:FooTest'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_testcase_spec(self):
        spec = 'test_foo.py:FooTest.test_bar'
        suite = BokChoyTestSuite('', test_spec=spec)
        name = 'tests/{}'.format(spec)
        self.assertEqual(suite.cmd, self._expected_command(name=name))

    def test_spec_with_draft_default_store(self):
        spec = 'test_foo.py'
        suite = BokChoyTestSuite('', test_spec=spec, default_store='draft')
        name = 'tests/{}'.format(spec)
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=name, store='draft')
        )

    def test_invalid_default_store(self):
        # the cmd will dumbly compose whatever we pass in for the default_store
        suite = BokChoyTestSuite('', default_store='invalid')
        name = 'tests'
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=name, store='invalid')
        )

    def test_serversonly(self):
        suite = BokChoyTestSuite('', serversonly=True)
        self.assertEqual(suite.cmd, "")

    def test_verify_xss(self):
        suite = BokChoyTestSuite('', verify_xss=True)
        name = 'tests'
        self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=True))

    def test_verify_xss_env_var(self):
        self.env_var_override.set('VERIFY_XSS', 'False')
        with self.env_var_override:
            suite = BokChoyTestSuite('')
            name = 'tests'
            self.assertEqual(suite.cmd, self._expected_command(name=name, verify_xss=False))

    def test_test_dir(self):
        test_dir = 'foo'
        suite = BokChoyTestSuite('', test_dir=test_dir)
        self.assertEqual(
            suite.cmd,
            self._expected_command(name=test_dir)
        )

    def test_verbosity_settings_1_process(self):
        """
        Using 1 process means paver should ask for the traditional xunit plugin for plugin results
        """
        expected_verbosity_string = (
            "--with-xunit --xunit-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml --verbosity=2".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else ''
            )
        )
        suite = BokChoyTestSuite('', num_processes=1)
        self.assertEqual(BokChoyTestSuite.verbosity_processes_string(suite), expected_verbosity_string)

    def test_verbosity_settings_2_processes(self):
        """
        Using multiple processes means specific xunit, coloring, and process-related settings should
        be used.
        """
        process_count = 2
        expected_verbosity_string = (
            "--with-xunitmp --xunitmp-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml"
            " --processes={procs} --no-color --process-timeout=1200".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else '',
                procs=process_count
            )
        )
        suite = BokChoyTestSuite('', num_processes=process_count)
        self.assertEqual(BokChoyTestSuite.verbosity_processes_string(suite), expected_verbosity_string)

    def test_verbosity_settings_3_processes(self):
        """
        With the above test, validate that num_processes can be set to various values
        """
        process_count = 3
        expected_verbosity_string = (
            "--with-xunitmp --xunitmp-file={repo_dir}/reports/bok_choy{shard_str}/xunit.xml"
            " --processes={procs} --no-color --process-timeout=1200".format(
                repo_dir=REPO_DIR,
                shard_str='/shard_' + self.shard if self.shard else '',
                procs=process_count
            )
        )
        suite = BokChoyTestSuite('', num_processes=process_count)
        self.assertEqual(BokChoyTestSuite.verbosity_processes_string(suite), expected_verbosity_string)

    def test_invalid_verbosity_and_processes(self):
        """
        If an invalid combination of verbosity and number of processors is passed in, a
        BuildFailure should be raised
        """
        suite = BokChoyTestSuite('', num_processes=2, verbosity=3)
        with self.assertRaises(BuildFailure):
            BokChoyTestSuite.verbosity_processes_string(suite)