示例#1
0
def setup_environ():

    """
    This func will import the required modules and set up enough of an
    appengine environment to let some of our management commands run inside the
    SDK sandbox
    """

    # Find the path on which the SDK is installed
    test_path = distutils.spawn.find_executable('dev_appserver.py')
    if test_path is None:  # pragma: no cover
        print "ERROR: Can't find appengine SDK on your PATH"
        sys.exit(1)
    sdk_path = os.path.dirname(os.readlink(test_path) if os.path.islink(test_path) else test_path)

    # add the SDK path to the system path
    sys.path.insert(0, sdk_path)

    # Use dev_appserver to set up the python path
    if 'google-cloud-sdk' in sdk_path:
        sdk_path = os.path.join(os.path.split(sdk_path)[0], 'platform', 'google_appengine')
        sys.path.insert(0, os.path.abspath(sdk_path))
        from dev_appserver import fix_sys_path
    else:
        from dev_appserver import fix_sys_path
    fix_sys_path()
示例#2
0
def main(sdk_path, test_path):
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  suite = unittest.loader.TestLoader().discover(test_path,
                                                pattern="*_test.py")
  unittest.TextTestRunner(verbosity=2).run(suite)
示例#3
0
def run_tests():
    sys.path.insert(0, "/usr/local/google_appengine")
    import dev_appserver
    dev_appserver.fix_sys_path()
    loader = unittest.defaultTestLoader
    suite = loader.loadTestsFromNames(modules_with_tests)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#4
0
    def setUp(self):
        from main import app
        if not AppEngineTestCase.dev_appserver_fixed:
            warnings.filterwarnings('ignore', category=UserWarning)

            import appengine_config
            appengine_config.PRODUCTION_MODE = False
            import dev_appserver
            dev_appserver.fix_sys_path()
            AppEngineTestCase.dev_appserver_fixed = True

        # Flask apps testing. See: http://flask.pocoo.org/docs/testing/
        app.config['TESTING'] = True
        app.config['CSRF_ENABLED'] = False
        app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
        self.app = app
        self.new_client()

        # Setups app engine test bed. See: http://code.google.com/appengine/docs/python/tools/localunittesting.html#Introducing_the_Python_Testing_Utilities
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_user_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_search_stub()
        self.testbed.init_urlfetch_stub()

        import datahelper
        datahelper.put_later = self.put_later

        self.dirty_ndb = []

        import config
        config.security_wait = 0  # When we test user authentication, we don't want to slow down the tests with security sleeps
示例#5
0
def main(sdk_path, test_path):

    # If the sdk path points to a google cloud sdk installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sys.path.insert(0, os.path.join(sdk_path, 'platform/google_appengine'))
    else:
        sys.path.insert(0, sdk_path)
    sys.path.insert(0, '../../public/')
    #print(sys.path)
    # Ensure that the google.appengine.* packages are available
    # in tests as well as all bundled third-party packages.
    import dev_appserver
    dev_appserver.fix_sys_path()
    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print "Note: unable to import appengine_config."

    # Discover and run tests.
    suite = unittest.loader.TestLoader().discover(test_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#6
0
def main(sdk_path, test_path):
  # Get the appserver on the path.
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()

  # Copy datastore to new file.
  shutil.copyfile(TEST_DATASTORE, TEST_DATASTORE + "_tmp")

  # Set up datastore so we can test on meaningful data.
  t = testbed.Testbed()
  t.setup_env(True, application_id='dev~openmobiledata')
  t.activate()
  t.init_datastore_v3_stub(True, TEST_DATASTORE + "_tmp", False)
  t.init_memcache_stub()


  # Get correct Django version.
  from google.appengine.dist import use_library
  use_library('django', '1.2')

  suite = unittest2.loader.TestLoader().discover(test_path,
                                                 pattern='*_test.py')
  unittest2.TextTestRunner(verbosity=2).run(suite)

  t.deactivate()
示例#7
0
def main():
    #logging.basicConfig(level=logging.DEBUG)
    sys.path.insert(0, SDK_PATH)
    sys.path.insert(0, "stashboard")
    import dev_appserver
    dev_appserver.fix_sys_path()
    nose.main()
def fix_up_path():
    """Changes import path to make all dependencies import correctly.
    Performs the following:
    - Removes the 'google' module from sys.modules, if it exists, since
      this could cause the google.appengine... imports to fail.
    - Follow the symlink that puts dev_appserver.py on the user's path
      to find the App Engine SDK and add the SDK root to the path.
    - Import dev_appserver from the SDK and fix up the path for imports using
      dev_appserver.fix_sys_path.
    - Add the current git project root to the import path.
    """
    # May have namespace conflicts with google.appengine.api...
    # such as google.net.proto
    sys.modules.pop('google', None)

    # Find where dev_appserver.py is installed locally. If dev_appserver.py
    # is not on the path, then 'which' will return None.
    dev_appserver_on_path = test_utils.which('dev_appserver.py')
    if dev_appserver_on_path is None or not os.path.exists(dev_appserver_on_path):
        print >>sys.stderr, NO_DEVAPPSERVER_TEMPLATE % (dev_appserver_on_path,)
        raise SystemExit(1)

    real_path = os.path.realpath(dev_appserver_on_path)
    sys.path.insert(0, os.path.dirname(real_path))
    import dev_appserver
    # Use fix_sys_path to make all App Engine imports work
    dev_appserver.fix_sys_path()

    project_root = subprocess.check_output(
        ['git', 'rev-parse', '--show-toplevel']).strip()
    sys.path.insert(0, project_root)
示例#9
0
文件: test.py 项目: prcek/KVG
def run():
    sys.path.insert(0, "/usr/local/bin")
    import dev_appserver

    dev_appserver.fix_sys_path()
    suite = unittest.loader.TestLoader().discover(os.path.dirname(__file__))
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#10
0
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    site.addsitedir(os.path.join(os.getcwd(), 'lib'))
    import dev_appserver
    dev_appserver.fix_sys_path()
    suite = unittest.loader.TestLoader().discover(test_path, top_level_dir='.')
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#11
0
def setup():
    if os.path.exists('frankenserver/python'):
        sdk_path = 'frankenserver/python'
    else:  # running on travis
        sdk_path = '../google_appengine'

    # If the SDK path points to a Google Cloud SDK installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sdk_path = os.path.join(sdk_path, 'platform/google_appengine')

    # Make sure google.appengine.* modules are importable.
    fixup_paths(sdk_path)

    # Make sure all bundled third-party packages are available.
    import dev_appserver
    dev_appserver.fix_sys_path()
    from google.appengine.ext import vendor
    vendor.add('lib-local')
    vendor.add('lib-both')

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print('Note: unable to import appengine_config.')
示例#12
0
def main():
    up = os.path.dirname
    webkit_root = up(up(up(up(up(os.path.abspath(__file__))))))

    tester = Tester()
    tester.add_tree(os.path.join(webkit_root, 'Tools', 'Scripts'), 'webkitpy')
    tester.add_tree(os.path.join(webkit_root, 'Source', 'WebKit2', 'Scripts'), 'webkit2')

    tester.skip(('webkitpy.common.checkout.scm.scm_unittest',), 'are really, really, slow', 31818)
    if sys.platform == 'win32':
        tester.skip(('webkitpy.common.checkout', 'webkitpy.common.config', 'webkitpy.tool'), 'fail horribly on win32', 54526)

    # This only needs to run on Unix, so don't worry about win32 for now.
    appengine_sdk_path = '/usr/local/google_appengine'
    if os.path.exists(appengine_sdk_path):
        if not appengine_sdk_path in sys.path:
            sys.path.append(appengine_sdk_path)
        import dev_appserver
        from google.appengine.dist import use_library
        use_library('django', '1.2')
        dev_appserver.fix_sys_path()
        tester.add_tree(os.path.join(webkit_root, 'Tools', 'QueueStatusServer'))
    else:
        _log.info('Skipping QueueStatusServer tests; the Google AppEngine Python SDK is not installed.')

    return not tester.run()
示例#13
0
文件: run_tests.py 项目: rekab/papt
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    sys.path.append('pylib')
    import dev_appserver
    dev_appserver.fix_sys_path()
    suite = unittest.loader.TestLoader().discover(test_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#14
0
def main():
    """Runs the tests."""

    # TODO(sll): Check if the next dir is valid.
    sdk_path = os.path.join(os.getcwd(), "..", "oppia_runtime", "google_appengine_1.7.4", "google_appengine")
    sys.path.insert(0, sdk_path)

    import dev_appserver

    dev_appserver.fix_sys_path()

    root_dir = os.path.realpath(os.path.join(os.getcwd()))
    suite = unittest.loader.TestLoader().discover(root_dir, pattern="*_test.py", top_level_dir=root_dir)
    result = unittest.TextTestRunner(verbosity=2).run(suite)

    suite2 = unittest.loader.TestLoader().discover(root_dir, pattern="tests.py", top_level_dir=root_dir)
    result2 = unittest.TextTestRunner(verbosity=2).run(suite2)

    if result.errors or result.failures or result2.errors or result2.failures:
        raise Exception(
            "Functional test suite failed: %s errors, %s failures of "
            " %s tests run." % (len(result.errors), len(result.failures), result.testsRun)
        )

    if result.testsRun + result2.testsRun != EXPECTED_TEST_COUNT:
        raise Exception(
            "Expected %s tests to be run, not %s." % (EXPECTED_TEST_COUNT, result.testsRun + result2.testsRun)
        )
示例#15
0
def main(test_path, args):
    sdk_path = getenv('APP_ENGINE',
                      expanduser("~") + '/google-cloud-sdk/platform/google_appengine/')
    sys.path.insert(0, sdk_path) # add AppEngine SDK to path
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        #print "Note: unable to import appengine_config."
        print "..."

    # Discover and run tests.
    #suite = unittest.loader.TestLoader().discover(test_path)
    #unittest.TextTestRunner(verbosity=2).run(suite)

    if vars(args)["skipbasics"]:
        suite = unittest.loader.TestLoader().discover(test_path, pattern="*graphs*.py")
    else:
        suite = unittest.loader.TestLoader().discover(test_path, pattern="test*.py")

    unittest.TextTestRunner(verbosity=2).run(suite)
示例#16
0
def main(sdk_path, test_path, test_pattern):
    # If the SDK path points to a Google Cloud SDK installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sdk_path = os.path.join(sdk_path, 'platform/google_appengine')

    # Make sure google.appengine.* modules are importable.
    fixup_paths(sdk_path)

    # Make sure all bundled third-party packages are available.
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print('Note: unable to import appengine_config.')

    # Discover and run tests.
    suite = unittest.loader.TestLoader().discover(test_path, test_pattern)
    return unittest.TextTestRunner(verbosity=2).run(suite)
示例#17
0
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    import dev_appserver 
    dev_appserver.fix_sys_path()
    sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib')) 
    suite = unittest2.loader.TestLoader().discover(test_path)
    unittest2.TextTestRunner(verbosity=2).run(suite)
示例#18
0
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib'))
    sys.path.insert(1, os.path.join(os.path.abspath('.')))

    try:
        import config
    except ImportError:
        raise Exception('Unable to load config module. Paths are most likely screwed up. Current path is: %r and has %r' % (
            os.path.abspath('.'), os.listdir(os.path.abspath('.'))
        ))
    config.enable_debug_panel = False

    #
    # This must always be imported first.
    from flask import logging

    from main import app

    logger = logging.create_logger(app)

    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    logger.addHandler(console)

    suite = unittest.loader.TestLoader().discover(test_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#19
0
def main():
  if '--help' in sys.argv:
    print 'Usage: python runtests.py [-q|--quiet|-v|--verbose] [--exit_on_failure] [tests|functional_tests|contrib_tests]'
    return
  verbosity = 1
  exit_on_failure = '--exit_on_failure' in sys.argv
  if '-q' in sys.argv or '--quiet' in sys.argv:
    verbosity = 0
  if "-v" in sys.argv or '--verbose' in sys.argv:
    verbosity = 2
  if verbosity == 0:
    logging.disable(logging.CRITICAL)
  elif verbosity == 1:
    logging.disable(logging.ERROR)
  elif verbosity == 2:
    logging.basicConfig(level=logging.DEBUG)

  import dev_appserver
  dev_appserver.fix_sys_path()
  # Allow user to run a specific folder of tests
  if 'tests' in sys.argv:
    run('tests', verbosity, exit_on_failure)
  elif 'functional_tests' in sys.argv:
    run('functional_tests', verbosity, exit_on_failure)
  elif 'contrib_tests' in sys.argv:
    run('contrib_tests', verbosity, exit_on_failure)
  else:
    run('tests', verbosity, exit_on_failure)
    run('functional_tests', verbosity, exit_on_failure)
    run('contrib_tests', verbosity, exit_on_failure)
示例#20
0
def fix_sys_path(appengine_sdk_dir=None):
    """Update sys.path for appengine khan academy imports, also envvars."""
    if 'dev_appserver' in sys.modules:      # we've already fixed the path!
        return

    # This was originally copied  webapp/tools/appengine_tool_setup.py

    if 'SERVER_SOFTWARE' not in os.environ:
        os.environ['SERVER_SOFTWARE'] = 'Development'
    if 'CURRENT_VERSION' not in os.environ:
        os.environ['CURRENT_VERSION'] = '764.1'

    if not appengine_sdk_dir:
        appengine_sdk_dir = _discover_sdk_path()

    # We put this at the front of the path so 'import google' gets the
    # appengine 'google' module, not another, un-useful google module
    # that is installed as part of, say, the bigquery package.  In
    # fact, bigquery is so annoying it registers python to import the
    # (bad) google module at python-start time.  It uses pkgutil to do
    # that, so we can update __path__ to include our path if needed.
    for (module_name, module) in sys.modules.items():
        if module_name == 'google' and hasattr(module, '__path__'):
            # Fake appengine apps that expect 'google' to just be the
            # appengine google.
            module.__file__ = os.path.join(appengine_sdk_dir, 'google')
            # Update the pkgutil __path__ var to say that google.foo
            # imports should look in the appengine-sdk first.  cf.
            # http://stackoverflow.com/questions/2699287/what-is-path-useful-for
            module.__path__.insert(0, module.__file__)
    sys.path.insert(0, appengine_sdk_dir)

    # Delegate the real work to the dev_appserver logic in the actual SDK.
    import dev_appserver
    dev_appserver.fix_sys_path()
示例#21
0
def setup_gae(sdk_path):
    if sys.version_info < (2, 7,):
        return

    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
示例#22
0
def main(sdk_path, test_path):
    sys.path.insert(0, sdk_path)
    os.environ["GAE_SDK_ROOT"] = "/cygdrive/c/Program Files/Google/Cloud SDK/google-cloud-sdk/platform/google_appengine"
    import dev_appserver
    dev_appserver.fix_sys_path()
    suite = unittest.loader.TestLoader().discover(test_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#23
0
def setup_gae_sdk(sdk_path):
  """Modifies sys.path and to be able to use Python portion of GAE SDK.

  Once this is called, other functions from this module know where to find GAE
  SDK and any AppEngine included module can be imported. The change is global
  and permanent.
  """
  global _GAE_SDK_PATH
  if _GAE_SDK_PATH:
    raise ValueError('setup_gae_sdk was already called.')
  _GAE_SDK_PATH = sdk_path

  sys.path.insert(0, sdk_path)
  # Sadly, coverage may inject google.protobuf in the path. Forcibly expulse it.
  if 'google' in sys.modules:
    del sys.modules['google']

  import dev_appserver
  dev_appserver.fix_sys_path()
  for i in sys.path[:]:
    if 'jinja2-2.6' in i:
      sys.path.remove(i)

  # Make 'yaml' variable (defined on top of this module) point to loaded module.
  global yaml
  import yaml as yaml_module
  yaml = yaml_module
示例#24
0
def main(sdk_path, test_paths):
    if 'lib' not in sys.path:
        sys.path.insert(0, 'lib')

    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()

    suites = unittest2.TestSuite()
    for test_path in test_paths:
        suite = None
        # tests/ directory
        if os.path.isdir(test_path):
            suite = unittest2.loader.TestLoader().discover(test_path)
        # test_file.py
        elif os.path.isfile(test_path):
            test_path, test_file = test_path.rsplit(os.path.sep, 1)
            suite = unittest2.loader.TestLoader().discover(test_path, test_file)
        # tests.module.TestCase
        elif '/' not in test_path and '.' in test_path:
            suite = unittest2.loader.TestLoader().loadTestsFromName(test_path)

        if suite is not None:
            suites.addTest(suite)

    unittest2.TextTestRunner(verbosity=2).run(suites)
def append_paths():
    os.environ["SERVER_SOFTWARE"] = ""
    os.environ["CURRENT_VERSION_ID"] = ""

    # Poor-man's `which` command, to find out where appengine lives.
    for path in os.environ['PATH'].split(':'):
        if os.path.isdir(path) and 'dev_appserver.py' in os.listdir(path):
            break
    else:
        # Default to Mac's default location -- best we can do.
        path = ("/Applications/GoogleAppEngineLauncher.app/Contents/"
                "Resources/GoogleAppEngine-default.bundle/Contents/"
                "Resources/google_appengine")

    app_engine_path = os.path.join(os.path.dirname(path), 'google_appengine')
    if not os.path.isdir(app_engine_path):
        raise RuntimeError('%s is not a directory' % app_engine_path)

    sys.path.append(app_engine_path)
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Also append the root of the appengine tree so we can load things
    # like config_jinja
    sys.path.append(os.path.dirname(os.path.dirname(__file__)))
示例#26
0
def setup_environ():

    # lib
    sys.path.insert(0, os.path.join(ROOT_PATH, 'lib'))


    # SDK (this will be simpler if SDK is in the codebase)
    sdk_path = None
    for path in os.environ.get('PATH').split(os.pathsep):
        if 'dev_appserver.py' in os.listdir(path):
            test_path = os.path.join(path, 'dev_appserver.py')
            sdk_path = os.path.dirname(
                os.readlink(test_path) if \
                    os.path.islink(test_path) else test_path)
            break

    if not sdk_path:
        sys.stderr.write("Fatal: Can't find sdk_path")
        sys.exit(1)
    sys.path.insert(0, sdk_path)


    # Use dev_appserver to set up the python path
    from dev_appserver import fix_sys_path
    fix_sys_path()

    from google.appengine.tools import dev_appserver as tools_dev_appserver
    from google.appengine import dist


    # Parse `app.yaml`
    appinfo, url_matcher, from_cache = tools_dev_appserver.LoadAppConfig(
        ROOT_PATH, {}, default_partition='dev')
    app_id = appinfo.application

    # Useful for later scripts
    os.environ['APPLICATION_ID'] = app_id
    os.environ['APPLICATION_VERSION'] = appinfo.version

    # Third party libraries on the path
    if appinfo.libraries:
        for library in appinfo.libraries:
            try:
                dist.use_library(library.name, library.version)
            except ValueError, e:
                if library.name == 'django' and library.version == '1.4':
                    # Work around an SDK issue
                    print 'Warning: django 1.4 not recognised by dist, fixing python path'
                    sys.path.insert(0, os.path.join(sdk_path, 'lib', 'django-1.4'))
                else:
                    print 'Warning: Unsupported library:\n%s\n' % e

            # Extra setup for django
            if library.name == 'django':
                try:
                    import settings
                    from django.core.management import setup_environ
                    setup_environ(settings, original_settings_path='settings')
                except ImportError:
                    sys.stderr.write("\nWarning! Could not import django settings")
示例#27
0
def pypath():
    """ Setup the environment and python path for django and for dev_appserver.
    """

    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

    # Set up the python path using dev_appserver
    for path in os.environ.get('PATH').split(os.pathsep):
        if 'dev_appserver.py' in os.listdir(path):
            test_path = os.path.join(path, 'dev_appserver.py')
            sdk_path = os.path.dirname(os.readlink(test_path) 
                if os.path.islink(test_path) 
                else test_path)
            sys.path.insert(0, sdk_path)

            from dev_appserver import fix_sys_path
            from google.appengine import tools, dist 

            # Load config from app.yaml
            appinfo, _, _ = tools.dev_appserver.LoadAppConfig(
                os.path.normpath(os.path.abspath('.')) {}, default_partition='dev')

            fix_sys_path()

            # Add Django (and any libraries) defined in app.yaml
            if appinfo.libraries:
                for library in appinfo.libraries:
                    dist.use_library(library.name, library.version)
示例#28
0
def main():
    up = os.path.dirname
    webkit_root = up(up(up(up(up(os.path.abspath(__file__))))))

    tester = Tester()
    tester.add_tree(os.path.join(webkit_root, "Tools", "Scripts"), "webkitpy")

    # There is no WebKit2 on Windows, so we don't need to run WebKit2 unittests on it.
    if not (sys.platform.startswith("win") or sys.platform == "cygwin"):
        tester.add_tree(os.path.join(webkit_root, "Source", "WebKit2", "Scripts"), "webkit2")

    tester.skip(("webkitpy.common.checkout.scm.scm_unittest",), "are really, really, slow", 31818)
    if sys.platform.startswith("win"):
        tester.skip(
            ("webkitpy.common.checkout", "webkitpy.common.config", "webkitpy.tool"), "fail horribly on win32", 54526
        )

    # This only needs to run on Unix, so don't worry about win32 for now.
    appengine_sdk_path = "/usr/local/google_appengine"
    if os.path.exists(appengine_sdk_path):
        if not appengine_sdk_path in sys.path:
            sys.path.append(appengine_sdk_path)
        import dev_appserver
        from google.appengine.dist import use_library

        use_library("django", "1.2")
        dev_appserver.fix_sys_path()
        tester.add_tree(os.path.join(webkit_root, "Tools", "QueueStatusServer"))
    else:
        _log.info("Skipping QueueStatusServer tests; the Google AppEngine Python SDK is not installed.")

    return not tester.run()
示例#29
0
def main():
    sys.path.insert(0, os.environ.get('GAE_SDK'))
    import dev_appserver
    dev_appserver.fix_sys_path()

    suite = unittest.loader.TestLoader().discover('.')
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#30
0
def bootstrap(sdk_path):
    sys.path.insert(0, sdk_path)

    # Force the google module to reload, for some reason on windows this can sometimes point to the one in site-packages.
    import google
    reload(google)

    import dev_appserver
    dev_appserver.fix_sys_path()
    sys.path = [re.sub('webob_0_9', 'webob_1_1_1', x) for x in sys.path]

    import fix_imports
    (fix_imports)

    # Activate a testbed so that httplib2 always knows that it's in app engine
    from google.appengine.ext import testbed
    testbed = testbed.Testbed()
    testbed.activate()
    testbed.init_urlfetch_stub()

    # Remove agressive logging
    rootLogger = logging.getLogger()
    for handler in rootLogger.handlers:
        if isinstance(handler, logging.StreamHandler):
            rootLogger.removeHandler(handler)
示例#31
0
def flush_memcache(app_name):
    """Flushes memcache for the server.

    Args:
        app_name: str. The name of the GCloud project.

    Returns:
        bool. True if memcache is flushed successfully, false otherwise.
    """
    import dev_appserver
    dev_appserver.fix_sys_path()

    from google.appengine.ext.remote_api import remote_api_stub
    from google.appengine.api import memcache

    remote_api_stub.ConfigureRemoteApiForOAuth('%s.appspot.com' % app_name,
                                               '/_ah/remote_api')
    return memcache.flush_all()
示例#32
0
def setup_cloud_sdk_paths():
    """Set up Cloud SDK on `sys.path`.

  Requires `$APPENGINE_SDK_DIR` be set to your App Engine SDK directory at
  `google-cloud-sdk/platform/google_appengine`.

  Useful for setting up tests that require App Engine stubs.
  """
    paths_need_setup = not any(
        ['google_appengine' in path for path in sys.path])
    if paths_need_setup:
        import os
        gae_dir = os.environ.get('APPENGINE_SDK_DIR')
        assert gae_dir is not None, 'Please set $APPENGINE_SDK_DIR'
        sys.path.append(gae_dir)
        # importing dev_appserver handles adding rest of libraries to sys.path
        import dev_appserver
        dev_appserver.fix_sys_path()
示例#33
0
def setup_test_env(sdk_path):
  """Sets up App Engine/Django test environment."""
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  # google.appengine.ext.testbed.Testbed should set SERVER_SOFTWARE
  # and APPLICATION_ID environment variables, but we need them
  # earlier when Django import settings.py.
  os.environ['SERVER_SOFTWARE'] = 'DevTestrunner'  # used in settings.py
  os.environ['APPLICATION_ID'] = 'test-codereview'  # used in settings.py
  os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
  # Provide a dummy value for REQUEST_ID_HASH in environment. This is
  # needed for now to make appstats happy (see comments on
  # http://codereview.appspot.com/5305060/).
  os.environ['REQUEST_ID_HASH'] = 'testing'
  from google.appengine.dist import use_library
  use_library('django', '1.2')
def main(sdk_path, test_path, third_party_path=None):
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    if third_party_path:
        sys.path.insert(0, third_party_path)

    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print "Note: unable to import appengine_config."

    suite = unittest2.loader.TestLoader().discover(test_path,
                                                   pattern='*_test.py')
    result = unittest2.TextTestRunner(verbosity=2).run(suite)
    if len(result.errors) > 0 or len(result.failures) > 0:
        sys.exit(1)
示例#35
0
def main(sdk_path, test_path, webtest_path):
    if not os.path.exists(sdk_path):
        return 'Missing %s: try grunt shell:getPythonTestDeps.' % sdk_path
    if not os.path.exists(test_path):
        return 'Missing %s: try grunt build.' % test_path
    if not os.path.exists(webtest_path):
        return 'Missing %s: try grunt shell:getPythonTestDeps.' % webtest_path

    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    sys.path.append(webtest_path)
    if not _WebTestIsInstalled():
        return 1
    suite = unittest.loader.TestLoader().discover(test_path,
                                                  pattern="*test.py")
    ok = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()
    return 0 if ok else 1
示例#36
0
def _fix_sys_path_for_appengine(pretest_filename):
  infra_base_dir = os.path.abspath(pretest_filename)
  pos = infra_base_dir.rfind('/infra/appengine')
  if pos == -1:
    return
  infra_base_dir = infra_base_dir[:pos + len('/infra')]

  # Remove the base infra directory from the path, since this isn't available
  # on appengine.
  sys.path.remove(infra_base_dir)

  # Add the google_appengine directory.
  sys.path.insert(0,
      os.path.join(os.path.dirname(infra_base_dir),
          'gcloud', 'platform', 'google_appengine'))

  import dev_appserver as pretest_dev_appserver
  pretest_dev_appserver.fix_sys_path()
示例#37
0
def main():
    try:
        import dev_appserver
    except ImportError:
        print >> sys.stderr, _gae_sdk_not_on_python_path_message
        raise

    dev_appserver.fix_sys_path()

    try:
        import webtest  # pylint: disable=W0612
    except ImportError:
        print >> sys.stderr, _webtest_not_installed_message
        raise

    tests_path = os.path.dirname(sys.modules[__name__].__file__)
    suite = unittest.loader.TestLoader().discover(tests_path,
                                                  pattern='*_test.py')
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#38
0
def main(sdk_path, test_path, module=None):
    p = dirname(abspath(test_path))
    sys.path.append(p)
    sys.path.insert(0, sdk_path)
    sys.path.insert(0, 'lib')

    import dev_appserver

    dev_appserver.fix_sys_path()
    if module and module != 'all':
        suite = unittest.loader.TestLoader().discover(test_path,
                                                      pattern=module)
    else:
        suite = unittest.loader.TestLoader().discover(test_path)
    doctest_modules = ["tools"]
    for mod in doctest_modules:
        suite.addTests(doctest.DocTestSuite(mod))
    test_result = unittest.TextTestRunner(verbosity=2).run(suite)
    sys.exit(0 if test_result.wasSuccessful() else 1)
示例#39
0
def set_up_gae_environment(sdk_path):
    """Set up appengine SDK third-party imports.

    The App Engine SDK does terrible things to the global interpreter state.
    Because of this, this stuff can't be neatly undone. As such, it can't be
    a fixture.
    """
    if 'google' in sys.modules:
        # Some packages, such as protobuf, clobber the google
        # namespace package. This prevents that.
        reload_module(sys.modules['google'])

    # This sets up google-provided libraries.
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Fixes timezone and other os-level items.
    import google.appengine.tools.os_compat  # noqa: unused import
示例#40
0
def main(test_path, args):
    sdk_path = getenv(
        'APP_ENGINE',
        expanduser("~") + '/google-cloud-sdk/platform/google_appengine/')
    sys.path.insert(0, sdk_path)  # add AppEngine SDK to path
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        #print "Note: unable to import appengine_config."
        print "..."

    # Discover and run tests.
    #suite = unittest.loader.TestLoader().discover(test_path)
    #unittest.TextTestRunner(verbosity=2).run(suite)

    import subprocess
    contextCheck = "./scripts/buildarchivecontext.py -o -|cut -d'\"' -f2|sort|uniq -d"

    print "Checking jsonldcontext for duplicates"
    dups = subprocess.check_output(contextCheck, shell=True)
    if len(dups):
        print "Duplicate entries in jsonldcontext: %s" % dups
        sys.exit(1)
    print "No duplicates in jsonldcontext\n\n"

    if vars(args)["skipbasics"]:
        suite = unittest.loader.TestLoader().discover(test_path,
                                                      pattern="*graphs*.py")
    else:
        suite = unittest.loader.TestLoader().discover(test_path,
                                                      pattern="test*.py")

    res = unittest.TextTestRunner(verbosity=2).run(suite)

    count = len(res.failures) + len(res.errors)
    sys.exit(count)
示例#41
0
def main(args=None):
    """Runs the tests."""
    parsed_args = _PARSER.parse_args(args=args)

    for directory in common.DIRS_TO_ADD_TO_SYS_PATH:
        if not os.path.exists(os.path.dirname(directory)):
            raise Exception('Directory %s does not exist.' % directory)
        sys.path.insert(0, directory)

    # The devappserver function fixes the system path by adding certain google
    # appengine libraries that we need in oppia to the system path. The Google
    # Cloud SDK comes with certain packages preinstalled including webapp2,
    # jinja2, and pyyaml so this function makes sure that those libraries are
    # installed.
    import dev_appserver
    dev_appserver.fix_sys_path()

    # In the process of migrating Oppia from Python 2 to Python 3, we are using
    # both google app engine apis that are contained in the Google Cloud SDK
    # folder, and also google cloud apis that are installed in our
    # 'third_party/python_libs' directory. Therefore, there is a confusion of
    # where the google module is located and which google module to import from.
    # The following code ensures that the google module that python looks at
    # imports from the 'third_party/python_libs' folder so that the imports are
    # correct.
    if 'google' in sys.modules:
        google_path = os.path.join(THIRD_PARTY_PYTHON_LIBS_DIR, 'google')
        google_module = sys.modules['google']
        google_module.__path__ = [google_path]
        google_module.__file__ = os.path.join(google_path, '__init__.py')

    suites = create_test_suites(test_target=parsed_args.test_target)

    results = [
        unittest.TextTestRunner(verbosity=2).run(suite) for suite in suites
    ]

    for result in results:
        if result.errors or result.failures:
            raise Exception(
                'Test suite failed: %s tests run, %s errors, %s failures.' %
                (result.testsRun, len(result.errors), len(result.failures)))
示例#42
0
def main(sdk_path, test_pattern):
    start_time = time.time()

    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()

    suites = unittest2.loader.TestLoader().discover("tests", test_pattern)

    processes = []
    result_queue = multiprocessing.Queue()
    for suite in suites:
        process = multiprocessing.Process(target=start_suite,
                                          args=[suite, result_queue])
        process.start()
        processes.append(process)

    for process in processes:
        process.join()

    fail = False
    total_tests_run = 0
    while not result_queue.empty():
        test_output, tests_run, was_successful = result_queue.get()
        total_tests_run += tests_run
        print '-----------------------'
        print test_output
        if not was_successful:
            fail = True

    print "================================"
    print "Completed {} tests in: {} seconds".format(total_tests_run,
                                                     time.time() - start_time)
    if fail:
        print "TESTS FAILED!"
    else:
        print "TESTS PASSED!"
    print "================================"
    if fail:
        sys.exit(1)
    else:
        sys.exit(0)
示例#43
0
def main(sdk_path, test_path):
    """
    Run the tests using testrunner.py script in the project root directory.
    Usage: testrunner.py SDK_PATH TEST_PATH
    Run unit tests for App Engine apps.
    SDK_PATH    Path to the SDK installation
    TEST_PATH   Path to package containing test modules
    Options:
      -h, --help  show this help message and exit
    """

    sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libx'))
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    suite = unittest.loader.TestLoader().discover(test_path)
    result = unittest.TextTestRunner(verbosity=2).run(suite)
    exit_code = 0 if result.wasSuccessful() else 1
    sys.exit(exit_code)
示例#44
0
def setup_gae(gae_lib_root):
    """Try to load Google App Engine SDK on Python 2.7.

    It shouldn't try to import to load it with Pyhton 2.6; 
    dev_appserver exit on load with any other version than 2.7.

    setup_gae will fail quietly if it can't find the SDK.

    """
    if sys.version_info[0:2] != (2, 7,):
        return

    try:
        sys.path.insert(0, gae_lib_root)
        import dev_appserver
    except ImportError:
        print("Failed to load Google App Engine SDK.")
        print("Google App Engine related tests will be skipped.")
    else:
        dev_appserver.fix_sys_path()
示例#45
0
def connect_to_pro_server_by_remote_api(cfg, shell):
    if hasattr(cfg, "project_id") and cfg.project_id:
        project_id = cfg.project_id
    else:
        click.echo("[Error] Please set project_id in your config file")
        return
    if hasattr(cfg, "gae_sdk_path") and cfg.gae_sdk_path:
        sdk_path = cfg.gae_sdk_path
    else:
        sdk_path = "/usr/local/google_appengine"

    os.environ['SERVER_SOFTWARE'] = 'Development (devshell remote-api)/1.0'
    os.environ['HTTP_HOST'] = 'localhost'
    os.environ['GAE_SDK_ROOT'] = sdk_path
    python_path = subprocess.check_output("which python", shell=True)
    os.environ['PYTHONPATH'] = os.environ["GAE_SDK_ROOT"] + ':' + python_path

    try:
        import dev_appserver
        dev_appserver.fix_sys_path()
    except ImportError:
        click.echo(
            'Please make sure the App Engine SDK is in your PYTHONPATH.')
        raise

    if hasattr(cfg, "project_path") and cfg.project_path:
        path = os.path.abspath(os.path.expanduser(cfg.project_path))
        sys.path.insert(0, path)
    if hasattr(cfg, "remote_api_path") and cfg.remote_api_path:
        remote_entry = cfg.remote_api_path
    else:
        remote_entry = "/_ah/remote_api"

    from google.appengine.ext.remote_api import remote_api_stub
    remote_api_stub.ConfigureRemoteApiForOAuth(
        '{}.appspot.com'.format(project_id), remote_entry)

    click.secho("\nYou are connecting to the production server, be careful!\n",
                bold=True,
                fg="red")
    start_shell(shell, globals(), locals())
示例#46
0
def main(sdk_path, test_path):
    # If the sdk path points to a google cloud sdk installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sys.path.insert(0, os.path.join(sdk_path, 'platform/google_appengine'))
    else:
        sys.path.insert(0, sdk_path)

    # Ensure that the google.appengine.* packages are available
    # in tests as well as all bundled third-party packages.
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print "Note: unable to import appengine_config."

    from google.appengine.ext import testbed

    testbed = testbed.Testbed()
    testbed.activate()
    testbed.init_app_identity_stub()
    testbed.init_datastore_v3_stub()
    testbed.init_user_stub()
    testbed.init_memcache_stub()

    # Discover and run tests.
    suite = unittest.loader.TestLoader().discover(test_path)

    for root, dirs, files in os.walk(test_path):
        for name in dirs:
            # print(os.path.join(root,name))
            suite.addTests(unittest.loader.TestLoader().discover(
                os.path.join(root, name)))

    unittest.TextTestRunner(verbosity=2).run(suite)
示例#47
0
def _SetupPaths():
    """Sets up the sys.path with special directories for endpointscfg.py."""
    sdk_path = _FindSdkPath()
    if sdk_path:
        sys.path.append(sdk_path)
        try:
            import dev_appserver  # pylint: disable=g-import-not-at-top
            if hasattr(dev_appserver, 'fix_sys_path'):
                dev_appserver.fix_sys_path()
            else:
                logging.warning(_NO_FIX_SYS_PATH_WARNING)
        except ImportError:
            logging.warning(_IMPORT_ERROR_WARNING)
    else:
        logging.warning(_NOT_FOUND_WARNING)

    # Add the path above this directory, so we can import the endpoints package
    # from the user's app code (rather than from another, possibly outdated SDK).
    # pylint: disable=g-import-not-at-top
    from google.appengine.ext import vendor
    vendor.add(os.path.dirname(os.path.dirname(__file__)))
示例#48
0
def main(sdk_path):
    path = os.path.realpath(__file__)
    tests_path = '/tests'
    lib__path = '/lib'
    if tests_path not in path:
        tests_path = '\\tests'
        lib__path = '\\lib'

    base = path[:path.index(tests_path)]

    sys.path.insert(1, base)
    sys.path.insert(1, base + lib__path)
    sys.path.insert(1, sdk_path)
    #sys.path.insert(1, '/usr/local/google_appengine/lib')
    #sys.path.insert(1, '/usr/local/google_appengine/lib/yaml/lib')

    import dev_appserver
    dev_appserver.fix_sys_path()

    suite = unittest.loader.TestLoader().discover(base + tests_path)
    unittest.TextTestRunner(verbosity=2).run(suite)
示例#49
0
def main(sdk_path, test_path):
    if 'SERVER_SOFTWARE' not in os.environ:
        os.environ['SERVER_SOFTWARE'] = 'Development'
    if 'CURRENT_VERSION' not in os.environ:
        os.environ['CURRENT_VERSION'] = '764.1'

    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()
    top_project_dir = os.path.abspath(
        os.path.dirname(os.path.realpath(__file__)))
    sys.path.insert(0, os.path.join(top_project_dir, "api/packages"))
    sys.path.insert(0, os.path.join(top_project_dir, "api/packages/flask.zip"))

    loader = unittest2.loader.TestLoader()
    if test_path.endswith('.py'):
        suite = loader.loadTestsFromName(file_path_to_module(test_path))
    else:
        suite = loader.discover(test_path, pattern=TEST_FILE_RE)

    unittest2.TextTestRunner(verbosity=2).run(suite)
示例#50
0
    def configure(self, options, conf):
        super(NoseGunit, self).configure(options, conf)

        if not self.enabled:
            return

        if sys.version_info[0:2] < (2, 5):
            raise EnvironmentError(
                "Python version must be greater than 2.5. Current running: %s"
                % sys.version)

        if options.gae_lib_path:
            self.gae_path = options.gae_lib_path
            sys.path.append(self.gae_path)

        current_path = sys.path[:]

        from dev_appserver import fix_sys_path
        fix_sys_path()

        sys.path.extend(current_path)
示例#51
0
def run_tests(sdk_path, *args):
    sys.path.insert(0, sdk_path)
    import dev_appserver
    dev_appserver.fix_sys_path()

    loader = unittest.loader.TestLoader()
    suites = []
    # Shared tests.
    shared_directory = os.path.dirname(os.path.realpath(__file__))
    shared_tests = os.path.join(shared_directory, "tests")
    suites.append(loader.discover(shared_tests, top_level_dir=os.getcwd()))
    # Project-specific tests.
    suites.append(loader.discover("tests", top_level_dir=os.getcwd()))

    for suite in suites:
        test_result = unittest.TextTestRunner(verbosity=2).run(suite)
        if not test_result.wasSuccessful():
            print "ERROR: Unit tests failed."
            return False

    return True
示例#52
0
def main():
    """Runs the tests."""
    def _iterate(test_suite_or_case):
        """Iterate through all the test cases in `test_suite_or_case`."""
        try:
            suite = iter(test_suite_or_case)
        except TypeError:
            yield test_suite_or_case
        else:
            for test in suite:
                for subtest in _iterate(test):
                    yield subtest

    feconf.PLATFORM = 'gae'

    for directory in DIRS_TO_ADD_TO_SYS_PATH:
        if not os.path.exists(os.path.dirname(directory)):
            raise Exception('Directory %s does not exist.' % directory)
        sys.path.insert(0, directory)

    import dev_appserver
    dev_appserver.fix_sys_path()

    parsed_args = _PARSER.parse_args()
    suites = create_test_suites(parsed_args.test_target)

    results = [
        unittest.TextTestRunner(verbosity=2).run(suite) for suite in suites
    ]

    tests_run = 0
    for result in results:
        tests_run += result.testsRun
        if result.errors or result.failures:
            raise Exception(
                'Test suite failed: %s tests run, %s errors, %s failures.' %
                (result.testsRun, len(result.errors), len(result.failures)))

    if tests_run == 0:
        raise Exception('No tests were run.')
示例#53
0
def fix_path():
    """ Set up the python path using dev_appserver """

    sdk_path, test_path = '', ''

    for path in os.environ.get('PATH').split(os.pathsep):
        # We except an OSError as there could be a
        # non-existent path in $PATH which would cause
        # listdir to fail. This is apparent on cloudbees
        # jenkins for example.
        try:
            if 'dev_appserver.py' in os.listdir(path):
                test_path = os.path.join(path, 'dev_appserver.py')
                sdk_path = os.path.dirname(
                    os.readlink(test_path) if os.path.islink(test_path
                                                             ) else test_path)
                sys.path.insert(0, sdk_path)
                from dev_appserver import fix_sys_path, GOOGLE_SQL_EXTRA_PATHS
                fix_sys_path(extra_extra_paths=GOOGLE_SQL_EXTRA_PATHS)
                customize_path()
        except OSError:
            continue
示例#54
0
def main():
    global _webkit_root
    configure_logging(logger=_log)

    up = os.path.dirname
    _webkit_root = up(up(up(up(up(os.path.abspath(__file__))))))

    tester = Tester()
    tester.add_tree(os.path.join(_webkit_root, 'Tools', 'Scripts'), 'webkitpy')

    # There is no WebKit2 on Windows, so we don't need to run WebKit2 unittests on it.
    if not (sys.platform.startswith('win') or sys.platform == 'cygwin'):
        tester.add_tree(
            os.path.join(_webkit_root, 'Source', 'WebKit', 'Scripts'),
            'webkit')

    tester.skip(('webkitpy.common.checkout.scm.scm_unittest', ),
                'are really, really, slow', 31818)
    if sys.platform.startswith('win'):
        tester.skip(('webkitpy.common.checkout', 'webkitpy.common.config',
                     'webkitpy.tool'), 'fail horribly on win32', 54526)

    # This only needs to run on Unix, so don't worry about win32 for now.
    appengine_sdk_path = '/usr/local/google_appengine'
    if os.path.exists(appengine_sdk_path):
        if not appengine_sdk_path in sys.path:
            sys.path.append(appengine_sdk_path)
        import dev_appserver
        from google.appengine.dist import use_library
        use_library('django', '1.2')
        dev_appserver.fix_sys_path()
        tester.add_tree(
            os.path.join(_webkit_root, 'Tools', 'QueueStatusServer'))
    else:
        _log.info(
            'Skipping QueueStatusServer tests; the Google AppEngine Python SDK is not installed.'
        )

    return not tester.run()
示例#55
0
def setup_stubs():

    GAE_HOME = os.environ.get('GAE_HOME')
    if not GAE_HOME:
        print "Set environment variable GAE_HOME pointing to AppEngine SDK."
        sys.exit(0)

    if not os.path.exists(os.path.join(GAE_HOME, "dev_appserver.py")):
        print "The environment variable GAE_HOME doesn't point to AppEngine SDK."
        sys.exit(0)

    from kalapy.conf import settings
    sys.path = [os.path.join(settings.PROJECT_DIR, 'lib'), GAE_HOME] + sys.path

    from dev_appserver import fix_sys_path
    fix_sys_path()
    from google.appengine.tools.dev_appserver import SetupStubs, LoadAppConfig
    from google.appengine.tools.dev_appserver_main import ParseArguments

    args, option_dict = ParseArguments(['', settings.PROJECT_DIR])
    config, matcher = LoadAppConfig(settings.PROJECT_DIR, {})
    SetupStubs(config.application, **option_dict)
示例#56
0
文件: gae_suite.py 项目: sp2703/oppia
def main(args=None):
    """Runs the tests."""
    parsed_args = _PARSER.parse_args(args=args)

    for directory in DIRS_TO_ADD_TO_SYS_PATH:
        if not os.path.exists(os.path.dirname(directory)):
            raise Exception('Directory %s does not exist.' % directory)
        sys.path.insert(0, directory)

    import dev_appserver
    dev_appserver.fix_sys_path()

    suites = create_test_suites(test_target=parsed_args.test_target)

    results = [unittest.TextTestRunner(verbosity=2).run(suite)
               for suite in suites]

    for result in results:
        if result.errors or result.failures:
            raise Exception(
                'Test suite failed: %s tests run, %s errors, %s failures.' % (
                    result.testsRun, len(result.errors), len(result.failures)))
示例#57
0
def main(sdk_path, test_path, test_pattern):
    # If the SDK path points to a Google Cloud SDK installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sdk_path = os.path.join(sdk_path, 'platform/google_appengine')

    # Make sure google.appengine.* modules are importable.
    fixup_paths(sdk_path)

    # Make sure all bundled third-party packages are available.
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        (appengine_config)
    except ImportError:
        print('Note: unable to import appengine_config.')

    # Discover and run tests.
    suite = unittest.loader.TestLoader().discover(test_path, test_pattern)
    return unittest.TextTestRunner(verbosity=2).run(suite)
示例#58
0
def setup_gae_sdk(sdk_path):
    """Modifies sys.path and other global process state to be able to use GAE SDK.

  Once this is called, other functions from this module know where to find GAE
  SDK and any AppEngine included module can be imported. The change is global
  and permanent.
  """
    global _GAE_SDK_PATH
    if _GAE_SDK_PATH:
        raise ValueError('setup_gae_sdk was already called.')
    _GAE_SDK_PATH = sdk_path

    sys.path.insert(0, sdk_path)
    # Sadly, coverage may inject google.protobuf in the path. Forcibly expulse it.
    if 'google' in sys.modules:
        del sys.modules['google']

    import dev_appserver
    dev_appserver.fix_sys_path()

    # Make 'yaml' variable (defined on top of this module) point to loaded module.
    global yaml
    import yaml as yaml_module
    yaml = yaml_module
示例#59
0
def main(sdk_path, test_path, test_pattern, start_pubsub):
    if start_pubsub:
        start_pubsub_emulator(sdk_path)
    # If the SDK path points to a Google Cloud SDK installation
    # then we should alter it to point to the GAE platform location.
    if os.path.exists(os.path.join(sdk_path, 'platform/google_appengine')):
        sdk_path = os.path.join(sdk_path, 'platform/google_appengine')
    #
    # # Make sure google.appengine.* modules are importable.
    fixup_paths(sdk_path)
    #
    # # Make sure all bundled third-party packages are available.
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Loading appengine_config from the current project ensures that any
    # changes to configuration there are available to all tests (e.g.
    # sys.path modifications, namespaces, etc.)
    try:
        import appengine_config
        (appengine_config)
    except ImportError:
        print('Note: unable to import appengine_config.')

    # Disable logging when running tests
    logging.disable(logging.CRITICAL)

    # Discover and run tests.
    suite = unittest.loader.TestLoader().discover(test_path, test_pattern)
    result = unittest.TextTestRunner(verbosity=2).run(suite)

    if len(_pubsub) != 0:
        _pubsub['proc'].terminate()
        _pubsub['dev'].close()

    return result
示例#60
0
def main():
    filesystem = FileSystem()
    wkf = WebKitFinder(filesystem)
    tester = Tester(filesystem, wkf)
    tester.add_tree(wkf.path_from_webkit_base('Tools', 'Scripts'), 'webkitpy')

    tester.skip(('webkitpy.common.checkout.scm.scm_unittest',), 'are really, really, slow', 31818)
    if sys.platform == 'win32':
        tester.skip(('webkitpy.common.checkout', 'webkitpy.common.config', 'webkitpy.tool', 'webkitpy.w3c', 'webkitpy.layout_tests.layout_package.bot_test_expectations'), 'fail horribly on win32', 54526)

    # This only needs to run on Unix, so don't worry about win32 for now.
    appengine_sdk_path = '/usr/local/google_appengine'
    if os.path.exists(appengine_sdk_path):
        if not appengine_sdk_path in sys.path:
            sys.path.append(appengine_sdk_path)
        import dev_appserver
        from google.appengine.dist import use_library
        use_library('django', '1.2')
        dev_appserver.fix_sys_path()
        tester.add_tree(wkf.path_from_webkit_base('Tools', 'TestResultServer'))
    else:
        _log.info('Skipping TestResultServer tests; the Google AppEngine Python SDK is not installed.')

    return not tester.run()