Using nose plugin to pass a boolean to my package

2019-02-28 15:51发布

问题:

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

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

EDITED CODE

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

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

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

from setEnvironment import env

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

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

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

SETUP.PY

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'
            ]
        }
    )

回答1:

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

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

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