当前位置: 首页>>代码示例>>Python>>正文


Python EnvironmentVarGuard.set方法代码示例

本文整理汇总了Python中test.test_support.EnvironmentVarGuard.set方法的典型用法代码示例。如果您正苦于以下问题:Python EnvironmentVarGuard.set方法的具体用法?Python EnvironmentVarGuard.set怎么用?Python EnvironmentVarGuard.set使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在test.test_support.EnvironmentVarGuard的用法示例。


在下文中一共展示了EnvironmentVarGuard.set方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TwilioTest

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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
开发者ID:swoloszynski,项目名称:kitcat,代码行数:27,代码来源:tests.py

示例2: SettingsTest

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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)
开发者ID:nbailey,项目名称:quark,代码行数:29,代码来源:tests.py

示例3: AWSEnvironmentVarGuard

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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
开发者ID:bodylabs,项目名称:baiji,代码行数:13,代码来源:test_config.py

示例4: MonitorTest

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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())
开发者ID:csakoda,项目名称:docker-readonly-proxy,代码行数:20,代码来源:test_monitor.py

示例5: TestPaverBokChoyCmd

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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)
#.........这里部分代码省略.........
开发者ID:AndreySonetico,项目名称:edx-platform,代码行数:103,代码来源:test_paver_bok_choy_cmds.py

示例6: TestEnvironmentProjectKeychain

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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()
开发者ID:cdcarter,项目名称:CumulusCI,代码行数:63,代码来源:test_keychain.py

示例7: JobsTest

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
class JobsTest(TestCase):

    def setUp(self):
        self.user = User.objects.create_user("ninja", "[email protected]", "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="ninja", password="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")
开发者ID:PabloCastellano,项目名称:alterchef,代码行数:71,代码来源:tests.py

示例8: TestPaverBokChoyCmd

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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,
#.........这里部分代码省略.........
开发者ID:digitalsatori,项目名称:edx-platform,代码行数:103,代码来源:test_paver_bok_choy_cmds.py

示例9: TestPaverBokChoyCmd

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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",
        ]
#.........这里部分代码省略.........
开发者ID:hastexo,项目名称:edx-platform,代码行数:103,代码来源:test_paver_bok_choy_cmds.py

示例10: ConfigurationTest

# 需要导入模块: from test.test_support import EnvironmentVarGuard [as 别名]
# 或者: from test.test_support.EnvironmentVarGuard import set [as 别名]
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):
#.........这里部分代码省略.........
开发者ID:rahulg963,项目名称:cachet-url-monitor,代码行数:103,代码来源:test_configuration.py


注:本文中的test.test_support.EnvironmentVarGuard.set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。