使用鼻子插件将布尔值传递给我的包 [英] Using nose plugin to pass a boolean to my package

查看:92
本文介绍了使用鼻子插件将布尔值传递给我的包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用鼻子测试时可以将变量从cmd移至我的模块吗?

Can a variable be moved from the cmd to my module when using nose tests?

方案:我正在使用硒运行测试,需要同时针对网站的生产版本和沙盒版本(www.sandbox.myurl.com和www.myurl.com)运行

Scenario: I am running tests with selenium that need to run against both production and sandbox versions of the website (www.sandbox.myurl.com and www.myurl.com)

我写了一个自定义的鼻子插件,让我设置要在哪个环境下运行

I wrote a custom nose plugin that lets me set which environment to run against

已编辑代码

env = None

class EnvironmentSelector(Plugin):
"""Selects if test will be run against production or sandbox environments.
"""

def __init__(self):
    Plugin.__init__(self)
    self.environment = "spam"  ## runs against sandbox by default

def options(self, parser, env):
    """Register command line options"""
    parser.add_option("--set-env",
                      action="store",
                      dest="setEnv",
                      metavar="ENVIRON",
                      help="Run tests against production or sandbox"
                      "If no --set-env specified, runs against sandbox by default")

def configure(self, options, config):
    """Configure the system, based on selected options."""

    #set variable to that which was passed in cmd
    self.environment = options.setEnv
    self.enabled = True

    global env
    print "This is env before: " + str(env)
    env = self.passEnv()
    print "This is env after: " str(env)
    return env

def passEnv(self):
    run_production = False

    if self.environment.lower() == "sandbox":
        print ("Environment set to sandbox")
        return run_production

    elif self.environment.lower() == "prod":
        print ("Environmnet set to prod")
        run_production = True
        return run_production

    else:
        print ("NO environment was set, running sandbox by default")
        return run_production

在我的程序包中,我有一个@setup函数,该函数在运行测试套件之前将适当的URL传递给webdriver.

In my package, I have a @setup function that passes the appropriate URL to the webdriver before running the test suite.

在装有我的setup()的模块顶部,我有

At the top of the module with my setup() in it, I have

from setEnvironment import env

我在设置函数中包含了一个值为env的打印语句

I included a print statement with the value of env in the setup function

虽然在setEnvironment.py中将env设置为True,但将其导入为None,这是env的原始分配.

Whiles env gets set in setEnvironment.py as True, it gets imported as None, which was env's original assignment.

如何获取变量以成功导入到@setup中?

How do I get the variable to successfully import into @setup??

SETUP.PY

这是我每次对setEnvironment脚本进行调整时要运行的内容.

Here's what I run everytime I make an adjustment to the setEnvironment script.

from setuptools import setup

setup(
    name='Custom nose plugins',
    version='0.6.0',
    description = 'setup Prod v. Sandbox environment',
    py_modules = ['setEnvironment'],
    entry_points = {
        'nose.plugins': [
            'setEnvironment = setEnvironment:EnvironmentSelector'
            ]
        }
    )

推荐答案

看起来就像您在执行操作时一样,变量的值是在导入时分配的. 尝试这样的事情:

It looks like the way you are doing it the value of the variable is assigned on import. Try something like this:

#at the top of the setup() module
import setEnvironment
...

#in setup() directly
print "env =", setEnvironment.env

您的代码中也有一些小的错别字.以下应该可以工作(setEnvironment.py):

You also have some minor typos in your code. The following should work (setEnvironment.py):

from nose.plugins.base import Plugin

env = None

class EnvironmentSelector(Plugin):
    """Selects if test will be run against production or sandbox environments.
    """

    def __init__(self):
        Plugin.__init__(self)
        self.environment = "spam"  ## runs against sandbox by default

    def options(self, parser, env):
        """Register command line options"""
        parser.add_option("--set-env",
                          action="store",
                          dest="setEnv",
                          metavar="ENVIRON",
                          help="Run tests against production or sandbox"
                          "If no --set-env specified, runs against sandbox by default")

    def configure(self, options, config):
        """Configure the system, based on selected options."""

        #set variable to that which was passed in cmd
        self.environment = options.setEnv
        self.enabled = self.environment

        if self.enabled:
            global env
            print "This is env before: " + str(env)
            env = self.passEnv()
            print "This is env after: " + str(env)
            return env

    def passEnv(self):
        run_production = False

        if self.environment.lower() == "sandbox":
            print ("Environment set to sandbox")
            return run_production

        elif self.environment.lower() == "prod":
            print ("Environmnet set to prod")
            run_production = True
            return run_production

        else:
            print ("NO environment was set, running sandbox by default")
            return run_production

这是我的测试代码(pg_test.py),可与纯Python一起运行:

And here is my testing code (pg_test.py), to run with straight python:

import logging
import sys

import nose

from nose.tools import with_setup

import setEnvironment

def custom_setup():
    #in setup() directly
    print "env =", setEnvironment.env


@with_setup(custom_setup)
def test_pg():
    pass

if __name__ == '__main__':   
    module_name = sys.modules[__name__].__file__

    logging.debug("running nose for package: %s", module_name)
    result = nose.run(argv=[sys.argv[0],
                            module_name,
                            '-s',
                            '--nologcapture',
                            '--set-env=prod'
                            ],
                      addplugins=[setEnvironment.EnvironmentSelector()],)
    logging.info("all tests ok: %s", result)

当我运行它时,我得到了:

And when I ran it, I got:

$ python pg_test.py
This is env before: None
Environmnet set to prod
This is env after: True
env = True
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

这篇关于使用鼻子插件将布尔值传递给我的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆