<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import sys

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))

if ROOT_PATH not in sys.path:
    sys.path.append(ROOT_PATH)

DEBUG = False
TEMPLATE_DEBUG = DEBUG

SITE_ID = 1
SITE_BRANDING = 'OpenStack'
SITE_NAME = 'openstack'
ENABLE_VNC = True

LOGIN_URL = '/auth/login'
LOGIN_REDIRECT_URL = '/'

MEDIA_ROOT = os.path.abspath(os.path.join(ROOT_PATH, '..', 'media'))
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.abspath(os.path.join(ROOT_PATH, '..', 'static'))
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'

CREDENTIAL_AUTHORIZATION_DAYS = '5'

ROOT_URLCONF = 'openstack_dashboard.urls'

HORIZON_CONFIG = {
    'dashboards': ('nova', 'syspanel', 'settings',),
    'default_dashboard': 'nova',
    'user_home': 'openstack_dashboard.views.user_home',
    'ajax_queue_limit': 10
}

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'openstack_dashboard.middleware.DashboardLogUnhandledExceptionsMiddleware',
    'horizon.middleware.HorizonMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
    'horizon.context_processors.horizon',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'horizon.loaders.TemplateLoader'
)

TEMPLATE_DIRS = (
    os.path.join(ROOT_PATH, 'templates'),
)

STATICFILES_FINDERS = (
    'compressor.finders.CompressorFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

less_binary = os.path.join(
        os.path.dirname(__file__), '..', 'bin', 'less', 'lessc')
COMPRESS_PRECOMPILERS = (
    ('text/less', (less_binary + ' {infile} {outfile}')),
)

COMPRESS_CSS_FILTERS = (
    'compressor.filters.css_default.CssAbsoluteFilter',
)

COMPRESS_ENABLED = True
COMPRESS_OUTPUT_DIR = 'dashboard'
COMPRESS_CSS_HASHING_METHOD = 'hash'

INSTALLED_APPS = (
    'openstack_dashboard',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'compressor',
    'horizon',
    'horizon.dashboards.nova',
    'horizon.dashboards.syspanel',
    'horizon.dashboards.settings',
)

AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_SECURE = False

TIME_ZONE = None
gettext_noop = lambda s: s
LANGUAGES = (
    ('en', gettext_noop('English')),
    ('it', gettext_noop('Italiano')),
    ('es', gettext_noop('Spanish')),
    ('fr', gettext_noop('French')),
    ('ja', gettext_noop('Japanese')),
    ('pt', gettext_noop('Portuguese')),
    ('pl', gettext_noop('Polish')),
    ('zh-cn', gettext_noop('Simplified Chinese')),
    ('zh-tw', gettext_noop('Traditional Chinese')),
)
LANGUAGE_CODE = 'en'
USE_I18N = True

OPENSTACK_KEYSTONE_DEFAULT_ROLE = 'Member'

DEFAULT_EXCEPTION_REPORTER_FILTER = 'horizon.exceptions.HorizonReporterFilter'

try:
    from local.local_settings import *
except ImportError:
    logging.warning("No local_settings file found.")

if DEBUG:
    logging.basicConfig(level=logging.DEBUG)
<commit_msg>Dependency Reconcilliation<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import sys

ROOT_PATH = os.path.dirname(os.path.abspath(__file__))

if ROOT_PATH not in sys.path:
    sys.path.append(ROOT_PATH)

DEBUG = False
TEMPLATE_DEBUG = DEBUG

SITE_ID = 1
SITE_BRANDING = 'OpenStack'
SITE_NAME = 'openstack'
ENABLE_VNC = True

LOGIN_URL = '/auth/login'
LOGIN_REDIRECT_URL = '/'

MEDIA_ROOT = os.path.abspath(os.path.join(ROOT_PATH, '..', 'media'))
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.abspath(os.path.join(ROOT_PATH, '..', 'static'))
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'

CREDENTIAL_AUTHORIZATION_DAYS = '5'

ROOT_URLCONF = 'openstack_dashboard.urls'

HORIZON_CONFIG = {
    'dashboards': ('nova', 'syspanel', 'settings',),
    'default_dashboard': 'nova',
    'user_home': 'openstack_dashboard.views.user_home',
    'ajax_queue_limit': 10
}

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'openstack_dashboard.middleware.DashboardLogUnhandledExceptionsMiddleware',
    'horizon.middleware.HorizonMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
    'horizon.context_processors.horizon',
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'horizon.loaders.TemplateLoader'
)

TEMPLATE_DIRS = (
    os.path.join(ROOT_PATH, 'templates'),
)

STATICFILES_FINDERS = (
    'compressor.finders.CompressorFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

less_binary = os.path.join(
        os.path.dirname(__file__), '..', 'bin', 'less', 'lessc')
COMPRESS_PRECOMPILERS = (
    ('text/less', (less_binary + ' {infile} {outfile}')),
)

COMPRESS_CSS_FILTERS = (
    'compressor.filters.css_default.CssAbsoluteFilter',
)

COMPRESS_ENABLED = True
COMPRESS_OUTPUT_DIR = 'dashboard'
COMPRESS_CSS_HASHING_METHOD = 'hash'
COMPRESS_PARSER = 'compressor.parser.HtmlParser'

INSTALLED_APPS = (
    'openstack_dashboard',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'compressor',
    'horizon',
    'horizon.dashboards.nova',
    'horizon.dashboards.syspanel',
    'horizon.dashboards.settings',
)

AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_SECURE = False

TIME_ZONE = None
gettext_noop = lambda s: s
LANGUAGES = (
    ('en', gettext_noop('English')),
    ('it', gettext_noop('Italiano')),
    ('es', gettext_noop('Spanish')),
    ('fr', gettext_noop('French')),
    ('ja', gettext_noop('Japanese')),
    ('pt', gettext_noop('Portuguese')),
    ('pl', gettext_noop('Polish')),
    ('zh-cn', gettext_noop('Simplified Chinese')),
    ('zh-tw', gettext_noop('Traditional Chinese')),
)
LANGUAGE_CODE = 'en'
USE_I18N = True

OPENSTACK_KEYSTONE_DEFAULT_ROLE = 'Member'

DEFAULT_EXCEPTION_REPORTER_FILTER = 'horizon.exceptions.HorizonReporterFilter'

try:
    from local.local_settings import *
except ImportError:
    logging.warning("No local_settings file found.")

if DEBUG:
    logging.basicConfig(level=logging.DEBUG)
<|endoftext|>


<commit_before>#!/usr/bin/python
"""Build an executable with PyInstaller."""
from __future__ import print_function
import sys
from os.path import dirname, abspath, join
from os import path, mkdir, chdir, listdir
import shutil
import argparse
import subprocess
import zipfile
import yaml
import codecs
import traceback

PY3 = sys.version_info >= (3, 0)
if PY3:
    unicode_str = str
else:
    unicode_str = unicode  # flake8: noqa

if sys.platform.startswith('win'):
    _PLATFORM = "windows"
elif sys.platform == "darwin":
    _PLATFORM = "osx"
else:
    _PLATFORM = "linux"

SPEC = '''# -*- mode: python -*-
a = Analysis(%(main)s,
             pathex=%(directory)s,
             hiddenimports=%(hidden)s,
             hookspath=%(hook)s,
             runtime_hooks=None)
a.datas = %(data)s
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=%(exe)s,
          debug=False,
          strip=None,
          icon=%(icon)s,
          console=%(gui)s)
'''

OSX_GUI_SPEC = '''
app = BUNDLE(exe,
             name=%(exe)s,
             icon=%(icon)s)
'''

class BuildVars(object):

    """Build variables."""

    extras = 'buildextras.yml'
    hidden_imports_to_crawl = []
    data_to_crawl = []
    hidden_imports = []
    data = []
    hookpaths = []
    paths = []

    def crawl_data(self):
        """Crawl data."""

        for target in self.data_to_crawl:
            if path.isfile(target):
                self.data.append((target, "./%s" % target, "DATA"))
            else:
                for f in listdir(target):
                    file_path = path.join(target, f)
                    if path.isfile(file_path) and not f.startswith((".", "~")) and not f.endswith('.py'):
                        name = '/'.join([target, f])
                        self.data.append((name, "./%s" % name, "DATA"))

    def crawl_hidden_imports(self):
        """Crawl hidden imports."""

        import pkgutil
        for mod in self.hidden_imports_to_crawl:
            pkg = pkgutil.get_loader(mod)
            if getattr(pkg, 'archive', None) is None:
                folder = pkg.filename
                self.hidden_imports.append(pkg.fullname)
                for f in listdir(folder):
                    if f != "__init__.py" and f.endswith('.py'):
                        self.hidden_imports.append('.'.join([pkg.fullname, f]))
            else:
                handle_egg(pkg.archive)

    def handle_egg(archive):
        """Handle an egg import."""

        def is_egg(archive):
            """Check if is an egg that we will accept."""

            egg_extension = "py%d.%d.egg" % (sys.version_info.major, sys.version_info.minor)
            return (
                path.isfile(archive) and
                path.basename(archive).endswith(egg_extension)
            )

        def hidden_egg_modules(archive):
            """Add egg modules to hidden imports."""

            with zipfile.ZipFile(archive, 'r') as z:
                text = z.read(z.getinfo('EGG-INFO/SOURCES.txt'))
                if PY3:
                    text = text.decode('utf-8')
                for line in text.split('\n'):
                    line = line.replace('\r', '')
                    if (
                        line.endswith('.py') and
                        not line.endswith('/__init__.py') and
                        line != 'setup.py'
                    ):
                        self.hidden_imports.append(line.replace('/', '.')[:-3])

        if is_egg(archive):
            self.paths.append(archive)
            hidden_egg_modules(archive)

    def print_vars(self, label, src):
        """Print specified variable."""

        print("--- %s ---" % label)
        for s in src:
            print(s)
        print('')

    def print_all_vars(self):
        """Print all the variables."""

        print('====== Processed Spec Variables =====')
        self.print_vars('Data', self.data)
        self.print_vars('Hidden Imports', self.hidden_imports)
        self.print_vars("Paths", self.paths)
        self.print_vars("Hooks", self.hookpaths)

    def read(self):
        """Read the build vars."""

        config = None
        if path.exists(self.extras):
            try:
                with codecs.open(self.extras, 'r', encoding='utf-8') as f:
                    config = yaml.load(f.read())
            except Exception:
                print(traceback.format_exc())
                config = None

        if config is not None:
            print(config)
            self.data_to_crawl.extend(config.get('data_to_crawl', []))
            self.hidden_imports_to_crawl.extend(config.get('hidden_imports_to_crawl', []))
            self.data.extend(config.get('data', []))
            self.hidden_imports.extend(config.get('hidden_imports', []))
            self.paths.extend(config.get('paths', []))
            self.hookpaths.extend(config.get('hookpaths', []))

        self.crawl_data()
        self.crawl_hidden_imports()

def build_spec_file(obj, gui):
    """Build the spec file."""
    proj_path = path.dirname(obj.script)
    sys.path.append(proj_path)

    build_vars = BuildVars()
    build_vars.read()

    build_vars.print_all_vars()
    spec = SPEC % {
        "main": repr([obj.script]),
        "directory": repr([path.dirname(obj.script)] + build_vars.paths),
        "hidden": repr(build_vars.hidden_imports),
        "hook": repr(build_vars.hookpaths),
        "data": repr(build_vars.data),
        "exe": repr(path.basename(obj.app)),
        "icon": repr(obj.icon),
        "gui": repr(not gui)
    }

    if gui and _PLATFORM == "osx":
        spec += OSX_GUI_SPEC % {
            "icon": repr(obj.icon),
            "exe": repr(path.basename(obj.app) + '.app')
        }

    with open("%s.spec" % obj.name, "w") as f:
        f.write(spec)

class Args(object):

    """Argument object."""

    def __init__(
        self, script, name, gui, clean, ext,
        icon=None, portable=False
    ):
        """Build arguments."""

        self.gui = bool(gui)
        self.name = name
        self.clean = bool(clean)
        self.icon = abspath(icon) if icon is not None else icon
        self.script = script
        self.extension = ext
        self.portable = portable

class BuildParams(object):

    """Build parametes."""

    python_bin_path = None
    python_executable = None
    pyinstaller_script = None
    out_dir = None
    script = None
    dist_path = None
    name = None
    clean = None
    extension = None
    icon = None
    portable = None
    spec_path = None

def parse_settings(args, obj):
    """Configure build parameters based on arguments."""

    err = False

    script_path = dirname(abspath(sys.argv[0]))
    obj.python_bin_path = dirname(sys.executable)
    obj.python_bin = sys.executable
    obj.pyinstaller_script = join(script_path, "pyinstaller", "pyinstaller.py")
    obj.out_dir = join(script_path, "build")
    obj.dist_path = join(script_path, "dist")
    obj.name = args.name
    obj.extension = args.extension
    obj.script = path.abspath(path.normpath(args.script))
    obj.icon = args.icon
    obj.clean = args.clean
    obj.portable = args.portable
    obj.spec = path.join(path.dirname(obj.script), '%s.spec' % obj.name)

    if not path.exists(obj.script):
        print("Could not find %s!" % obj.script)
        err = True
    elif args.icon is not None and not path.exists(args.icon):
        print("Could not find %s!" % obj.icon)
        err = True
    elif obj.pyinstaller_script is None or not path.exists(obj.pyinstaller_script):
        print("Could not find pyinstaller.py!")
        err |= True

    if not path.exists(obj.out_dir):
        err |= create_dir(obj.out_dir)
    elif not path.isdir(obj.out_dir):
        print("%s is not a directory!" % obj.out_dir)
        err |= True

    # Get executable name to build
    if not err:
        obj.app = path.join(obj.dist_path, obj.name) + obj.extension
    return err

def create_dir(directory):
    """Create build directory."""

    err = False
    try:
        print("Creating %s..." % directory)
        mkdir(directory)
    except:
        print("Could not create %s!" % directory)
        err = True
    return err

def clean_build(build_dir):
    """Clean the build directory."""

    err = False
    try:
        print("Cleaning %s..." % build_dir)
        shutil.rmtree(build_dir)
    except:
        print("Failed to clean %s!" % build_dir)
        err = True
    return err

def parse_options(args, obj):
    """Parse the build parameters and build the pyinstaller build command."""

    err = False

    # Parse Settings file
    if not err:
        err = parse_settings(args, obj)

    # See if cleaning is required
    if not err and args.clean and path.exists(obj.out_dir):
        err = clean_build(obj.out_dir)

    if not err:
        build_spec_file(obj, args.gui)

    # Construct build params for build processs
    if not err:
        obj.params = (
            [("python" if obj.portable else obj.python_bin), obj.pyinstaller_script, '-F'] +
            (['--clean'] if args.clean is not None else []) +
            (['-w', '--workpath=%s' % obj.out_dir] if args.gui else ['--workpath=%s' % obj.out_dir]) +
            ['--distpath=%s' % obj.dist_path] +
            ['-y', obj.spec]
            # ['--log-level=DEBUG']
        )
    return err

def build(obj):
    """Launch the build process."""

    err = False

    if obj.portable:
        chdir(obj.python_bin_path)

    # Setup build process
    process = subprocess.Popen(
        obj.params,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=False
    )

    for line in iter(process.stdout.readline, b''):
        sys.stdout.write(line.decode('utf-8') if PY3 else line)
    process.communicate()

    # Check for bad error code
    if process.returncode:
        print("Compilation failed!")
        err = True

    return err

def main():
    """Setup the build process and initiate it."""

    parser = argparse.ArgumentParser(prog='Build', description='Python script for building apps for Pyinstaller')
    # Flag arguments
    parser.add_argument('--version', action='version', version='%(prog)s 1.0.0')
    parser.add_argument('--clean', '-c', action='store_true', default=False, help='Clean build before re-building.')
    parser.add_argument('--gui', '-g', action='store_true', default=True, help='GUI app')
    parser.add_argument('--portable', '-p', action='store_true', default=False, help='Build with portable python (windows)')
    # parser.add_argument('--icon', '-i', default=None, nargs="?", help='App icon')
    parser.add_argument('--script', default="cli.py", help='Main script')
    parser.add_argument('--name', default="subclrschm", help='Name of app')
    inputs = parser.parse_args()
    if _PLATFORM == "windows":
        args = Args(
            inputs.script, inputs.name, inputs.gui, inputs.clean, ".exe", path.abspath("icons\\subclrschm.ico"), inputs.portable
        )
    elif _PLATFORM == "osx":
        args = Args(
            inputs.script, inputs.name, inputs.gui, inputs.clean, '', path.abspath("icons/subclrschm.icns")
        )
    else:
        args = Args(
            inputs.script, inputs.name, inputs.gui, inputs.clean, '', inputs.icon
        )

    # Parse options
    build_params = BuildParams()
    err = parse_options(args, build_params)

    # Build executable
    if not err:
        err = build(build_params)

    return err

if __name__ == "__main__":
    sys.exit(main())
<commit_msg>Update build script to the latest<commit_after>#!/usr/bin/python
"""Build an executable with PyInstaller."""
from __future__ import print_function
import sys
from os.path import dirname, abspath, join
from os import path, mkdir, chdir, listdir
import shutil
import argparse
import subprocess
import zipfile
import yaml
import codecs
import traceback

PY3 = sys.version_info >= (3, 0)
if PY3:
    unicode_str = str
else:
    unicode_str = unicode  # noqa

if sys.platform.startswith('win'):
    _PLATFORM = "windows"
elif sys.platform == "darwin":
    _PLATFORM = "osx"
else:
    _PLATFORM = "linux"

SPEC = '''# -*- mode: python -*-
a = Analysis(%(main)s,
             pathex=%(directory)s,
             hiddenimports=%(hidden)s,
             hookspath=%(hook)s,
             runtime_hooks=None)
a.datas = %(data)s
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=%(exe)s,
          debug=False,
          strip=None,
          icon=%(icon)s,
          console=%(gui)s)
'''

OSX_GUI_SPEC = '''
app = BUNDLE(exe,
             name=%(exe)s,
             icon=%(icon)s)
'''

class BuildVars(object):

    """Build variables."""

    extras = 'buildextras.yml'
    hidden_imports_to_crawl = []
    data_to_crawl = []
    hidden_imports = []
    data = []
    hookpaths = []
    paths = []

    def crawl_data(self):
        """Crawl data."""

        for target in self.data_to_crawl:
            if path.isfile(target):
                self.data.append((target, "./%s" % target, "DATA"))
            else:
                for f in listdir(target):
                    file_path = path.join(target, f)
                    if path.isfile(file_path) and not f.startswith((".", "~")) and not f.endswith('.py'):
                        name = '/'.join([target, f])
                        self.data.append((name, "./%s" % name, "DATA"))

    def crawl_hidden_imports(self):
        """Crawl hidden imports."""

        import pkgutil
        for mod in self.hidden_imports_to_crawl:
            pkg = pkgutil.get_loader(mod)
            if getattr(pkg, 'archive', None) is None:
                folder = pkg.filename
                self.hidden_imports.append(pkg.fullname)
                for f in listdir(folder):
                    if f != "__init__.py" and f.endswith('.py'):
                        self.hidden_imports.append('.'.join([pkg.fullname, f]))
            else:
                self.handle_egg(pkg.archive)

    def handle_egg(self, archive):
        """Handle an egg import."""

        def is_egg(archive):
            """Check if is an egg that we will accept."""

            egg_extension = "py%d.%d.egg" % (sys.version_info.major, sys.version_info.minor)
            return (
                path.isfile(archive) and
                path.basename(archive).endswith(egg_extension)
            )

        def hidden_egg_modules(archive):
            """Add egg modules to hidden imports."""

            with zipfile.ZipFile(archive, 'r') as z:
                text = z.read(z.getinfo('EGG-INFO/SOURCES.txt'))
                if PY3:
                    text = text.decode('utf-8')
                for line in text.split('\n'):
                    line = line.replace('\r', '')
                    if (
                        line.endswith('.py') and
                        not line.endswith('/__init__.py') and
                        line != 'setup.py'
                    ):
                        self.hidden_imports.append(line.replace('/', '.')[:-3])

        if is_egg(archive):
            self.paths.append(archive)
            hidden_egg_modules(archive)

    def print_vars(self, label, src):
        """Print specified variable."""

        print("--- %s ---" % label)
        for s in src:
            print(s)
        print('')

    def print_all_vars(self):
        """Print all the variables."""

        print('====== Processed Spec Variables =====')
        self.print_vars('Data', self.data)
        self.print_vars('Hidden Imports', self.hidden_imports)
        self.print_vars("Paths", self.paths)
        self.print_vars("Hooks", self.hookpaths)

    def read(self):
        """Read the build vars."""

        config = None
        if path.exists(self.extras):
            try:
                with codecs.open(self.extras, 'r', encoding='utf-8') as f:
                    config = yaml.load(f.read())
            except Exception:
                print(traceback.format_exc())
                config = None

        if config is not None:
            print(config)
            self.data_to_crawl.extend(config.get('data_to_crawl', []))
            self.hidden_imports_to_crawl.extend(config.get('hidden_imports_to_crawl', []))
            self.data.extend(config.get('data', []))
            self.hidden_imports.extend(config.get('hidden_imports', []))
            self.paths.extend(config.get('paths', []))
            self.hookpaths.extend(config.get('hookpaths', []))

        self.crawl_data()
        self.crawl_hidden_imports()

def build_spec_file(obj, gui):
    """Build the spec file."""
    proj_path = path.dirname(obj.script)
    sys.path.append(proj_path)

    build_vars = BuildVars()
    build_vars.read()

    build_vars.print_all_vars()
    spec = SPEC % {
        "main": repr([obj.script]),
        "directory": repr([path.dirname(obj.script)] + build_vars.paths),
        "hidden": repr(build_vars.hidden_imports),
        "hook": repr(build_vars.hookpaths),
        "data": repr(build_vars.data),
        "exe": repr(path.basename(obj.app)),
        "icon": repr(obj.icon),
        "gui": repr(not gui)
    }

    if gui and _PLATFORM == "osx":
        spec += OSX_GUI_SPEC % {
            "icon": repr(obj.icon),
            "exe": repr(path.basename(obj.app) + '.app')
        }

    with open("%s.spec" % obj.name, "w") as f:
        f.write(spec)

class Args(object):

    """Argument object."""

    def __init__(self, script, name, **kwargs):
        """Build arguments."""

        icon = kwargs.get('icon', None)

        self.gui = bool(kwargs.get('gui', False))
        self.name = name
        self.clean = bool(kwargs.get('clean', False))
        self.icon = abspath(icon) if icon is not None else icon
        self.script = script
        self.extension = kwargs.get('ext', '')
        self.portable = kwargs.get('portable', False)

class BuildParams(object):

    """Build parametes."""

    python_bin_path = None
    python_executable = None
    pyinstaller_script = None
    out_dir = None
    script = None
    dist_path = None
    name = None
    clean = None
    extension = None
    icon = None
    portable = None
    spec_path = None

def parse_settings(args, obj):
    """Configure build parameters based on arguments."""

    err = False

    script_path = dirname(abspath(sys.argv[0]))
    obj.python_bin_path = dirname(sys.executable)
    obj.python_bin = sys.executable
    obj.pyinstaller_script = join(script_path, "pyinstaller", "pyinstaller.py")
    obj.out_dir = join(script_path, "build")
    obj.dist_path = join(script_path, "dist")
    obj.name = args.name
    obj.extension = args.extension
    obj.script = path.abspath(path.normpath(args.script))
    obj.icon = args.icon
    obj.clean = args.clean
    obj.portable = args.portable
    obj.spec = path.join(path.dirname(obj.script), '%s.spec' % obj.name)

    if not path.exists(obj.script):
        print("Could not find %s!" % obj.script)
        err = True
    elif args.icon is not None and not path.exists(args.icon):
        print("Could not find %s!" % obj.icon)
        err = True
    elif obj.pyinstaller_script is None or not path.exists(obj.pyinstaller_script):
        print("Could not find pyinstaller.py!")
        err |= True

    if not path.exists(obj.out_dir):
        err |= create_dir(obj.out_dir)
    elif not path.isdir(obj.out_dir):
        print("%s is not a directory!" % obj.out_dir)
        err |= True

    # Get executable name to build
    if not err:
        obj.app = path.join(obj.dist_path, obj.name) + obj.extension
    return err

def create_dir(directory):
    """Create build directory."""

    err = False
    try:
        print("Creating %s..." % directory)
        mkdir(directory)
    except:
        print("Could not create %s!" % directory)
        err = True
    return err

def clean_build(build_dir):
    """Clean the build directory."""

    err = False
    try:
        print("Cleaning %s..." % build_dir)
        shutil.rmtree(build_dir)
    except:
        print("Failed to clean %s!" % build_dir)
        err = True
    return err

def parse_options(args, obj):
    """Parse the build parameters and build the pyinstaller build command."""

    err = False

    # Parse Settings file
    if not err:
        err = parse_settings(args, obj)

    # See if cleaning is required
    if not err and args.clean and path.exists(obj.out_dir):
        err = clean_build(obj.out_dir)

    if not err:
        build_spec_file(obj, args.gui)

    # Construct build params for build processs
    if not err:
        obj.params = (
            [("python" if obj.portable else obj.python_bin), obj.pyinstaller_script, '-F'] +
            (['--clean'] if args.clean is not None else []) +
            (['-w', '--workpath=%s' % obj.out_dir] if args.gui else ['--workpath=%s' % obj.out_dir]) +
            ['--distpath=%s' % obj.dist_path] +
            ['-y', obj.spec]
            # ['--log-level=DEBUG']
        )
    return err

def build(obj):
    """Launch the build process."""

    err = False

    if obj.portable:
        chdir(obj.python_bin_path)

    # Setup build process
    process = subprocess.Popen(
        obj.params,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        shell=False
    )

    for line in iter(process.stdout.readline, b''):
        sys.stdout.write(line.decode('utf-8') if PY3 else line)
    process.communicate()

    # Check for bad error code
    if process.returncode:
        print("Compilation failed!")
        err = True

    return err

def main():
    """Setup the build process and initiate it."""

    parser = argparse.ArgumentParser(prog='Build', description='Python script for building apps for Pyinstaller')
    # Flag arguments
    parser.add_argument('--version', action='version', version='%(prog)s 1.0.0')
    parser.add_argument('--clean', '-c', action='store_true', default=False, help='Clean build before re-building.')
    parser.add_argument('--gui', '-g', action='store_true', default=True, help='GUI app')
    parser.add_argument(
        '--portable', '-p',
        action='store_true', default=False,
        help='Build with portable python (windows)'
    )
    # parser.add_argument('--icon', '-i', default=None, nargs="?", help='App icon')
    parser.add_argument('--script', default="cli.py", help='Main script')
    parser.add_argument('--name', default="subclrschm", help='Name of app')
    inputs = parser.parse_args()
    if _PLATFORM == "windows":
        args = Args(
            inputs.script, inputs.name, gui=inputs.gui, clean=inputs.clean,
            ext=".exe", icon=path.abspath("icons\\subclrschm.ico"), portable=inputs.portable
        )
    elif _PLATFORM == "osx":
        args = Args(
            inputs.script, inputs.name, gui=inputs.gui, clean=inputs.clean,
            ext='', icon=path.abspath("icons/subclrschm.icns")
        )
    else:
        args = Args(
            inputs.script, inputs.name, gui=inputs.gui, clean=inputs.clean,
            ext='', icon=inputs.icon
        )

    # Parse options
    build_params = BuildParams()
    err = parse_options(args, build_params)

    # Build executable
    if not err:
        err = build(build_params)

    return err

if __name__ == "__main__":
    sys.exit(main())
<|endoftext|>


<commit_before>#!/usr/bin/python2.7
import os, sys

SRC_DIR     = "src"
BIN_DIR     = "bin"
BIN_NAME    = "json"

INCL_PATH   = ["~/usr/include/", "~/usr/include/x86_64-linux-gnu/"]
LIB_PATH    = ["~/lib/", "~/usr/lib/", "~/usr/lib/x86_64-linux-gnu/"]

RFLAGS      = ["-O3", "-Wall", "-Wextra", "-Werror", "-Wformat",
                "-fno-gcse"]
DFLAGS      = ["-g", "-Wall", "-Wextra", "-Werror", "-Wformat",
                "-Wunreachable-code", "-Winline", "-fstack-protector"]
DLIBS       = ["m", "dl"]

def str_fmt(fmt, var):
    for k in var:
        fmt = fmt.replace("{%s}" % str(k), var[k])
    return fmt

def ls_dir(path):
    return [os.path.join(dp, f)
            for dp, dn, fn in
                os.walk(path) for f in fn]

def main():
    os.chdir(sys.path[0])

    compiler = "gcc"
    flags = RFLAGS

    for flag in sys.argv:
        if flag == "-gcc":
            compiler = "gcc"
        elif flag == "-clang":
            compiler = "clang"
        elif flag == "-d":
            flags = DFLAGS

    if not os.path.exists(BIN_DIR):
        os.makedirs(BIN_DIR)

    cfiles = filter(lambda x:x.endswith((".c", ".C")), ls_dir(SRC_DIR))
    cmd = str_fmt(
        "{compiler} {flags} -o {outfile} {srcfiles} {ipath} {lpath} {libs}",
        {
            "compiler"  : compiler,
            "flags"     : " ".join(flags),
            "outfile"   : BIN_DIR + "/" + BIN_NAME,
            "srcfiles"  : " ".join(cfiles),
            "ipath"     : " ".join(map(lambda x: "-I " + x, INCL_PATH)),
            "lpath"     : " ".join(map(lambda x: "-L " + x, LIB_PATH)),
            "libs"      : " ".join(map(lambda x: "-l " + x, DLIBS)),
        })
    print("compiling...")
    os.system(cmd)
    print("done!")

if __name__ == "__main__":
    main()

<commit_msg>removed build.py<commit_after><|endoftext|>


<commit_before>import os
import pytest

import dots.callbacks
from dots.environment import Env
from dots.interpreter import AsciiDotsInterpreter
from dots.exceptions import DotsExit

class KeepOutputIOCallbacks(dots.callbacks.IOCallbacksStorage):
    def __init__(self, env, input):
        super().__init__(env)

        self.output = []
        self.input = input

    def get_input(self, ascii_char=False):
        if ascii_char:
            chars_to_read = 1
            if len(self.input) == 0:
                return ""
        else:
            chars_to_read = self.input.find('\n')
            if chars_to_read == -1:
                chars_to_read = len(self.input)

        ret = self.input[:chars_to_read]
        self.input = self.input[chars_to_read:]
        print(ret, '-----', chars_to_read)
        return ret

    def on_output(self, value):
        self.output.append(value)

    def on_finish(self):
        pass

    def on_error(self, error_text):
        raise RuntimeError(error_text)

    def on_microtick(self, dot):
        "we're not printing anything at all"

def check_output(name, input='', run_in_parallel=True):
    env = Env()
    env.io = KeepOutputIOCallbacks(env, input)

    with open('test/' + name + '.dots', encoding='utf-8') as file:
        program = file.read()
    print(program, '---', sep='' )
    interpreter = AsciiDotsInterpreter(env, program, 'test', run_in_parallel)
    print(interpreter.env.world.map)
    try:
        interpreter.run()
    except DotsExit:
        pass

    return env.io.output

def map_add_newline(*args):
    """
    Transforms the list to a list of strings with a newline at the end of each entry, as this is a common pattern.
    """

    return list(str(arg) + '\n' for arg in args)

def test_dots_count_to_100():
    out = check_output('count_to_100')
    assert out == map_add_newline(*range(1, 101))

def test_dots_use_for_in_range_library():
    out = check_output('use_for_in_range')
    assert out == map_add_newline(*range(1, 10))

def test_dots_use_wraps():
    out = check_output('warps')
    assert out == map_add_newline(3)

def test_dots_print_three():
    out = check_output('three')
    assert out == map_add_newline(3)

def test_dots_quine():
    out = check_output('quine')
    with open('test/quine.dots') as f:
        assert ''.join(out) == f.read()

def test_dots_factor():
    out = check_output('factor', '24')
    assert out == map_add_newline(1, 2, 3, 4)

    out = check_output('factor', '51')
    assert out == map_add_newline(1, 3)

def test_dots_singleton():
    out = check_output('singleton')
    assert out == map_add_newline(*range(1, 6))

    out = check_output('singleton_2')
    assert out == map_add_newline(-1, 1)

def test_dots_and():
    out = check_output('and')
    assert out == map_add_newline('Good')

def test_dots_timing():
    out = check_output('lock')
    assert out == map_add_newline(1)

def test_dots_ascii_input():
    out = check_output('ascii_input', "END\n")
    assert out == map_add_newline('Success!')

def test_dots_filter_chars():
    out = check_output('filter_chars', "END\n")
    assert out == [0, 0, 1, 1]

def test_dots_eof():
    out = check_output('eof', "hi\n")
    assert len(out) == 5
<commit_msg>test: stop importing the installed library, but import the code files instead<commit_after>import os
import sys
import pytest

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dots import callbacks
from dots.environment import Env
from dots.interpreter import AsciiDotsInterpreter
from dots.exceptions import DotsExit

class KeepOutputIOCallbacks(callbacks.IOCallbacksStorage):
    def __init__(self, env, input):
        super().__init__(env)

        self.output = []
        self.input = input

    def get_input(self, ascii_char=False):
        if ascii_char:
            chars_to_read = 1
            if len(self.input) == 0:
                return ""
        else:
            chars_to_read = self.input.find('\n')
            if chars_to_read == -1:
                chars_to_read = len(self.input)

        ret = self.input[:chars_to_read]
        self.input = self.input[chars_to_read:]
        print(ret, '-----', chars_to_read)
        return ret

    def on_output(self, value):
        self.output.append(value)

    def on_finish(self):
        pass

    def on_error(self, error_text):
        raise RuntimeError(error_text)

    def on_microtick(self, dot):
        "we're not printing anything at all"

def check_output(name, input='', run_in_parallel=True):
    env = Env()
    env.io = KeepOutputIOCallbacks(env, input)

    with open('test/' + name + '.dots', encoding='utf-8') as file:
        program = file.read()
    print(program, '---', sep='' )
    interpreter = AsciiDotsInterpreter(env, program, 'test', run_in_parallel)
    print(interpreter.env.world.map)
    try:
        interpreter.run()
    except DotsExit:
        pass

    return env.io.output

def map_add_newline(*args):
    """
    Transforms the list to a list of strings with a newline at the end of each entry, as this is a common pattern.
    """

    return list(str(arg) + '\n' for arg in args)

def test_dots_count_to_100():
    out = check_output('count_to_100')
    assert out == map_add_newline(*range(1, 101))

def test_dots_use_for_in_range_library():
    out = check_output('use_for_in_range')
    assert out == map_add_newline(*range(1, 10))

def test_dots_use_wraps():
    out = check_output('warps')
    assert out == map_add_newline(3)

def test_dots_print_three():
    out = check_output('three')
    assert out == map_add_newline(3)

def test_dots_quine():
    out = check_output('quine')
    with open('test/quine.dots') as f:
        assert ''.join(out) == f.read()

def test_dots_factor():
    out = check_output('factor', '24')
    assert out == map_add_newline(1, 2, 3, 4)

    out = check_output('factor', '51')
    assert out == map_add_newline(1, 3)

def test_dots_singleton():
    out = check_output('singleton')
    assert out == map_add_newline(*range(1, 6))

    out = check_output('singleton_2')
    assert out == map_add_newline(-1, 1)

def test_dots_and():
    out = check_output('and')
    assert out == map_add_newline('Good')

def test_dots_timing():
    out = check_output('lock')
    assert out == map_add_newline(1)

def test_dots_ascii_input():
    out = check_output('ascii_input', "END\n")
    assert out == map_add_newline('Success!')

def test_dots_filter_chars():
    out = check_output('filter_chars', "END\n")
    assert out == [0, 0, 1, 1]

def test_dots_eof():
    out = check_output('eof', "hi\n")
    assert len(out) == 5
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
#   -*- coding: utf-8 -*-
#
#   This file is part of PyBuilder
#
#   Copyright 2011-2014 PyBuilder Team
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys

sys.path.insert(0, 'src/main/python')  # This is only necessary in PyBuilder sources for bootstrap

from pybuilder import bootstrap
from pybuilder.core import Author, init, use_bldsup, use_plugin

bootstrap()

use_plugin("pypi:pybuilder_external_plugin_demo")
use_plugin("python.core")
use_plugin("python.pytddmon")
use_plugin("python.distutils")
use_plugin("python.install_dependencies")

use_plugin("copy_resources")
use_plugin("filter_resources")
use_plugin("source_distribution")

use_plugin("python.coverage")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.flake8")
use_plugin("python.frosted")

if not sys.version_info[0:2] == (3, 2):
    use_plugin("python.cram")

use_plugin("python.pydev")
use_plugin("python.pycharm")
use_plugin("python.pytddmon")

use_bldsup()
use_plugin("pdoc")

summary = "An extensible, easy to use continuous build tool for Python"
description = """PyBuilder is a build automation tool for python.

PyBuilder is a software build tool written in pure Python which mainly targets Python applications.
It is based on the concept of dependency based programming but also comes along with powerful plugin mechanism that
allows the construction of build life cycles similar to those known from other famous build tools like Apache Maven.
"""

authors = [Author("Alexander Metzner", "alexander.metzner@gmail.com"),
           Author("Maximilien Riehl", "max@riehl.io"),
           Author("Michael Gruber", "aelgru@gmail.com"),
           Author("Udo Juettner", "udo.juettner@gmail.com")]
url = "http://pybuilder.github.io"
license = "Apache License"
version = "0.10.24"

default_task = ["analyze", "publish"]

@init
def initialize(project):
    project.build_depends_on("mockito-without-hardcoded-distribute-version")
    project.build_depends_on("mock")
    project.build_depends_on("pyfix")  # required test framework
    project.build_depends_on("pyassert")
    project.build_depends_on("wheel")
    project.build_depends_on("pdoc")
    project.build_depends_on("pygments")

    project.set_property("verbose", True)

    project.set_property("coverage_break_build", False)
    project.get_property("coverage_exceptions").append("pybuilder.cli")
    project.get_property("coverage_exceptions").append("pybuilder.plugins.core_plugin")

    project.set_property("copy_resources_target", "$dir_dist")
    project.get_property("copy_resources_glob").append("LICENSE")
    project.get_property("filter_resources_glob").append("**/pybuilder/__init__.py")

    project.set_property('flake8_break_build', True)
    project.set_property('flake8_include_test_sources', True)
    project.set_property('flake8_include_scripts', True)
    project.set_property('flake8_max_line_length', 130)

    project.set_property('frosted_include_test_sources', True)
    project.set_property('frosted_include_scripts', True)

    project.get_property("source_dist_ignore_patterns").append(".project")
    project.get_property("source_dist_ignore_patterns").append(".pydevproject")
    project.get_property("source_dist_ignore_patterns").append(".settings")

    # enable this to build a bdist on vagrant
    # project.set_property("distutils_issue8876_workaround_enabled", True)
    project.get_property("distutils_commands").append("bdist_wheel")
    project.set_property("distutils_classifiers", [
                         'Programming Language :: Python',
                         'Programming Language :: Python :: Implementation :: CPython',
                         'Programming Language :: Python :: Implementation :: PyPy',
                         'Programming Language :: Python :: 2.6',
                         'Programming Language :: Python :: 2.7',
                         'Programming Language :: Python :: 3',
                         'Programming Language :: Python :: 3.2',
                         'Programming Language :: Python :: 3.3',
                         'Programming Language :: Python :: 3.4',
                         'Development Status :: 4 - Beta',
                         'Environment :: Console',
                         'Intended Audience :: Developers',
                         'License :: OSI Approved :: Apache Software License',
                         'Topic :: Software Development :: Build Tools',
                         'Topic :: Software Development :: Quality Assurance',
                         'Topic :: Software Development :: Testing'])
<commit_msg>v0.10.25<commit_after>#!/usr/bin/env python
#
#   -*- coding: utf-8 -*-
#
#   This file is part of PyBuilder
#
#   Copyright 2011-2014 PyBuilder Team
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys

sys.path.insert(0, 'src/main/python')  # This is only necessary in PyBuilder sources for bootstrap

from pybuilder import bootstrap
from pybuilder.core import Author, init, use_bldsup, use_plugin

bootstrap()

use_plugin("pypi:pybuilder_external_plugin_demo")
use_plugin("python.core")
use_plugin("python.pytddmon")
use_plugin("python.distutils")
use_plugin("python.install_dependencies")

use_plugin("copy_resources")
use_plugin("filter_resources")
use_plugin("source_distribution")

use_plugin("python.coverage")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.flake8")
use_plugin("python.frosted")

if not sys.version_info[0:2] == (3, 2):
    use_plugin("python.cram")

use_plugin("python.pydev")
use_plugin("python.pycharm")
use_plugin("python.pytddmon")

use_bldsup()
use_plugin("pdoc")

summary = "An extensible, easy to use continuous build tool for Python"
description = """PyBuilder is a build automation tool for python.

PyBuilder is a software build tool written in pure Python which mainly targets Python applications.
It is based on the concept of dependency based programming but also comes along with powerful plugin mechanism that
allows the construction of build life cycles similar to those known from other famous build tools like Apache Maven.
"""

authors = [Author("Alexander Metzner", "alexander.metzner@gmail.com"),
           Author("Maximilien Riehl", "max@riehl.io"),
           Author("Michael Gruber", "aelgru@gmail.com"),
           Author("Udo Juettner", "udo.juettner@gmail.com")]
url = "http://pybuilder.github.io"
license = "Apache License"
version = "0.10.25"

default_task = ["analyze", "publish"]

@init
def initialize(project):
    project.build_depends_on("mockito-without-hardcoded-distribute-version")
    project.build_depends_on("mock")
    project.build_depends_on("pyfix")  # required test framework
    project.build_depends_on("pyassert")
    project.build_depends_on("wheel")
    project.build_depends_on("pdoc")
    project.build_depends_on("pygments")

    project.set_property("verbose", True)

    project.set_property("coverage_break_build", False)
    project.get_property("coverage_exceptions").append("pybuilder.cli")
    project.get_property("coverage_exceptions").append("pybuilder.plugins.core_plugin")

    project.set_property("copy_resources_target", "$dir_dist")
    project.get_property("copy_resources_glob").append("LICENSE")
    project.get_property("filter_resources_glob").append("**/pybuilder/__init__.py")

    project.set_property('flake8_break_build', True)
    project.set_property('flake8_include_test_sources', True)
    project.set_property('flake8_include_scripts', True)
    project.set_property('flake8_max_line_length', 130)

    project.set_property('frosted_include_test_sources', True)
    project.set_property('frosted_include_scripts', True)

    project.get_property("source_dist_ignore_patterns").append(".project")
    project.get_property("source_dist_ignore_patterns").append(".pydevproject")
    project.get_property("source_dist_ignore_patterns").append(".settings")

    # enable this to build a bdist on vagrant
    # project.set_property("distutils_issue8876_workaround_enabled", True)
    project.get_property("distutils_commands").append("bdist_wheel")
    project.set_property("distutils_classifiers", [
                         'Programming Language :: Python',
                         'Programming Language :: Python :: Implementation :: CPython',
                         'Programming Language :: Python :: Implementation :: PyPy',
                         'Programming Language :: Python :: 2.6',
                         'Programming Language :: Python :: 2.7',
                         'Programming Language :: Python :: 3',
                         'Programming Language :: Python :: 3.2',
                         'Programming Language :: Python :: 3.3',
                         'Programming Language :: Python :: 3.4',
                         'Development Status :: 4 - Beta',
                         'Environment :: Console',
                         'Intended Audience :: Developers',
                         'License :: OSI Approved :: Apache Software License',
                         'Topic :: Software Development :: Build Tools',
                         'Topic :: Software Development :: Quality Assurance',
                         'Topic :: Software Development :: Testing'])
<|endoftext|>


<commit_before># Copyright 2016 Raytheon BBN Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0

import unittest
import numpy as np

import auspex.pulsecal.phase_estimation as pe
import auspex.pulsecal.optimize_amplitude as oa

def simulate_measurement(amp, target, numPulses):

    idealAmp = 0.34
    noiseScale = 0.05
    polarization = 0.99 # residual polarization after each pulse

    # data representing over/under rotation of pi/2 pulse
    # theta = pi/2 * (amp/idealAmp);
    theta = target * (amp/idealAmp)
    ks = [ 2**k for k in range(0,numPulses+1)]

    xdata = [ polarization**x * np.sin(x*theta) for x in ks];
    xdata = np.insert(xdata,0,-1.0)
    zdata = [ polarization**x * np.cos(x*theta) for x in ks];
    zdata = np.insert(zdata,0,1.0)
    data = np.array([zdata,xdata]).flatten('F')
    data = np.tile(data,(2,1)).flatten('F')

    # add noise
    #data += noiseScale * np.random.randn(len(data));
    vardata = noiseScale**2 * np.ones((len(data,)));

    return data, vardata

class PhaseEstimateTestCase(unittest.TestCase):

    def test_simulated_measurement(self):

        numPulses = 9
        amp = .55
        direction = 'X'
        target = np.pi

        # Using the same simulated data as matlab
        data, vardata =  simulate_measurement(amp, target, numPulses)

        # Verify output matches what was previously seen by matlab
        phase, sigma = pe.phase_estimation(data, vardata, verbose=True)
        self.assertAlmostEqual(phase,-1.2012,places=4)
        self.assertAlmostEqual(sigma,0.0245,places=4)

class OptimizeAmplitudeTestCase(unittest.TestCase):

    def test_simulated_measurement(self):

        numPulses = 9
        amp = .55
        direction = 'X'
        target = np.pi

        # NOTE: this function is a place holder to simulate an AWG generating
        # a sequence and a digitizer receiving the sequence.  This function
        # is passed into the optimize_amplitude routine to be able to update
        # the amplitude as part of the optimization loop.
        def update_data(amp):
            data, vardata =  simulate_measurement(amp, target, numPulses)
            return data,vardata

        # Verify output matches what was previously seen by matlab
        amp_out = oa.optimize_amplitude(amp, direction, target, update_data)

        # NOTE: expected result is from the same input fed to the matlab
        # routine
        self.assertAlmostEqual(phase,0.3400,places=4)

if __name__ == '__main__':
    unittest.main()
<commit_msg>add assert for testing amp<commit_after># Copyright 2016 Raytheon BBN Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0

import unittest
import numpy as np

import auspex.pulsecal.phase_estimation as pe
import auspex.pulsecal.optimize_amplitude as oa

def simulate_measurement(amp, target, numPulses):

    idealAmp = 0.34
    noiseScale = 0.05
    polarization = 0.99 # residual polarization after each pulse

    # data representing over/under rotation of pi/2 pulse
    # theta = pi/2 * (amp/idealAmp);
    theta = target * (amp/idealAmp)
    ks = [ 2**k for k in range(0,numPulses+1)]

    xdata = [ polarization**x * np.sin(x*theta) for x in ks];
    xdata = np.insert(xdata,0,-1.0)
    zdata = [ polarization**x * np.cos(x*theta) for x in ks];
    zdata = np.insert(zdata,0,1.0)
    data = np.array([zdata,xdata]).flatten('F')
    data = np.tile(data,(2,1)).flatten('F')

    # add noise
    #data += noiseScale * np.random.randn(len(data));
    vardata = noiseScale**2 * np.ones((len(data,)));

    return data, vardata

class PhaseEstimateTestCase(unittest.TestCase):

    def test_simulated_measurement(self):

        numPulses = 9
        amp = .55
        direction = 'X'
        target = np.pi

        # Using the same simulated data as matlab
        data, vardata =  simulate_measurement(amp, target, numPulses)

        # Verify output matches what was previously seen by matlab
        phase, sigma = pe.phase_estimation(data, vardata, verbose=True)
        self.assertAlmostEqual(phase,-1.2012,places=4)
        self.assertAlmostEqual(sigma,0.0245,places=4)

class OptimizeAmplitudeTestCase(unittest.TestCase):

    def test_simulated_measurement(self):

        numPulses = 9
        amp = .55
        direction = 'X'
        target = np.pi

        # NOTE: this function is a place holder to simulate an AWG generating
        # a sequence and a digitizer receiving the sequence.  This function
        # is passed into the optimize_amplitude routine to be able to update
        # the amplitude as part of the optimization loop.
        def update_data(amp):
            data, vardata =  simulate_measurement(amp, target, numPulses)
            return data,vardata

        # Verify output matches what was previously seen by matlab
        amp_out = oa.optimize_amplitude(amp, direction, target, update_data)

        # NOTE: expected result is from the same input fed to the matlab
        # routine
        self.assertAlmostEqual(amp_out,0.3400,places=4)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
#   -*- coding: utf-8 -*-
#
#   This file is part of PyBuilder
#
#   Copyright 2011-2014 PyBuilder Team
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys

sys.path.insert(0, 'src/main/python')  # This is only necessary in PyBuilder sources for bootstrap

from pybuilder import bootstrap
from pybuilder.core import Author, init, use_bldsup, use_plugin

bootstrap()

use_plugin("pypi:pybuilder_external_plugin_demo")
use_plugin("python.core")
use_plugin("python.pytddmon")
use_plugin("python.distutils")
use_plugin("python.install_dependencies")

use_plugin("copy_resources")
use_plugin("filter_resources")
use_plugin("source_distribution")

use_plugin("python.coverage")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.flake8")
use_plugin("python.frosted")
use_plugin("python.jedi_linter")

if not sys.version_info[0:2] == (3, 2):
    use_plugin("python.cram")

use_plugin("python.pydev")
use_plugin("python.pycharm")
use_plugin("python.pytddmon")

use_bldsup()
use_plugin("pdoc")

summary = "An extensible, easy to use continuous build tool for Python"
description = """PyBuilder is a build automation tool for python.

PyBuilder is a software build tool written in pure Python which mainly targets Python applications.
It is based on the concept of dependency based programming but also comes along with powerful plugin mechanism that
allows the construction of build life cycles similar to those known from other famous build tools like Apache Maven.
"""

authors = [Author("Alexander Metzner", "alexander.metzner@gmail.com"),
           Author("Maximilien Riehl", "max@riehl.io"),
           Author("Michael Gruber", "aelgru@gmail.com"),
           Author("Udo Juettner", "udo.juettner@gmail.com")]
url = "http://pybuilder.github.io"
license = "Apache License"
version = "0.10.32"

default_task = ["analyze", "publish"]

@init
def initialize(project):
    project.build_depends_on("mockito-without-hardcoded-distribute-version")
    project.build_depends_on("fluentmock")
    project.build_depends_on("mock")
    project.build_depends_on("pyfix")  # required test framework
    project.build_depends_on("pyassert")
    project.build_depends_on("wheel")
    project.build_depends_on("pdoc")
    project.build_depends_on("pygments")

    project.set_property("verbose", True)

    project.set_property("coverage_break_build", False)
    project.get_property("coverage_exceptions").append("pybuilder.cli")
    project.get_property("coverage_exceptions").append("pybuilder.plugins.core_plugin")

    project.set_property('flake8_break_build', True)
    project.set_property('flake8_include_test_sources', True)
    project.set_property('flake8_include_scripts', True)
    project.set_property('flake8_max_line_length', 130)

    project.set_property('frosted_include_test_sources', True)
    project.set_property('frosted_include_scripts', True)

    project.set_property("copy_resources_target", "$dir_dist")
    project.get_property("copy_resources_glob").append("LICENSE")
    project.get_property("filter_resources_glob").append("**/pybuilder/__init__.py")

    project.get_property("source_dist_ignore_patterns").append(".project")
    project.get_property("source_dist_ignore_patterns").append(".pydevproject")
    project.get_property("source_dist_ignore_patterns").append(".settings")

    # enable this to build a bdist on vagrant
    # project.set_property("distutils_issue8876_workaround_enabled", True)
    project.get_property("distutils_commands").append("bdist_wheel")
    project.set_property("distutils_console_scripts", ["pyb_ = pybuilder.cli:main"])
    project.set_property("distutils_classifiers", [
                         'Programming Language :: Python',
                         'Programming Language :: Python :: Implementation :: CPython',
                         'Programming Language :: Python :: Implementation :: PyPy',
                         'Programming Language :: Python :: 2.6',
                         'Programming Language :: Python :: 2.7',
                         'Programming Language :: Python :: 3',
                         'Programming Language :: Python :: 3.2',
                         'Programming Language :: Python :: 3.3',
                         'Programming Language :: Python :: 3.4',
                         'Development Status :: 4 - Beta',
                         'Environment :: Console',
                         'Intended Audience :: Developers',
                         'License :: OSI Approved :: Apache Software License',
                         'Topic :: Software Development :: Build Tools',
                         'Topic :: Software Development :: Quality Assurance',
                         'Topic :: Software Development :: Testing'])
<commit_msg>v0.10.33<commit_after>#!/usr/bin/env python
#
#   -*- coding: utf-8 -*-
#
#   This file is part of PyBuilder
#
#   Copyright 2011-2014 PyBuilder Team
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import sys

sys.path.insert(0, 'src/main/python')  # This is only necessary in PyBuilder sources for bootstrap

from pybuilder import bootstrap
from pybuilder.core import Author, init, use_bldsup, use_plugin

bootstrap()

use_plugin("pypi:pybuilder_external_plugin_demo")
use_plugin("python.core")
use_plugin("python.pytddmon")
use_plugin("python.distutils")
use_plugin("python.install_dependencies")

use_plugin("copy_resources")
use_plugin("filter_resources")
use_plugin("source_distribution")

use_plugin("python.coverage")
use_plugin("python.unittest")
use_plugin("python.integrationtest")
use_plugin("python.flake8")
use_plugin("python.frosted")
use_plugin("python.jedi_linter")

if not sys.version_info[0:2] == (3, 2):
    use_plugin("python.cram")

use_plugin("python.pydev")
use_plugin("python.pycharm")
use_plugin("python.pytddmon")

use_bldsup()
use_plugin("pdoc")

summary = "An extensible, easy to use continuous build tool for Python"
description = """PyBuilder is a build automation tool for python.

PyBuilder is a software build tool written in pure Python which mainly targets Python applications.
It is based on the concept of dependency based programming but also comes along with powerful plugin mechanism that
allows the construction of build life cycles similar to those known from other famous build tools like Apache Maven.
"""

authors = [Author("Alexander Metzner", "alexander.metzner@gmail.com"),
           Author("Maximilien Riehl", "max@riehl.io"),
           Author("Michael Gruber", "aelgru@gmail.com"),
           Author("Udo Juettner", "udo.juettner@gmail.com")]
url = "http://pybuilder.github.io"
license = "Apache License"
version = "0.10.33"

default_task = ["analyze", "publish"]

@init
def initialize(project):
    project.build_depends_on("mockito-without-hardcoded-distribute-version")
    project.build_depends_on("fluentmock")
    project.build_depends_on("mock")
    project.build_depends_on("pyfix")  # required test framework
    project.build_depends_on("pyassert")
    project.build_depends_on("wheel")
    project.build_depends_on("pdoc")
    project.build_depends_on("pygments")

    project.set_property("verbose", True)

    project.set_property("coverage_break_build", False)
    project.get_property("coverage_exceptions").append("pybuilder.cli")
    project.get_property("coverage_exceptions").append("pybuilder.plugins.core_plugin")

    project.set_property('flake8_break_build', True)
    project.set_property('flake8_include_test_sources', True)
    project.set_property('flake8_include_scripts', True)
    project.set_property('flake8_max_line_length', 130)

    project.set_property('frosted_include_test_sources', True)
    project.set_property('frosted_include_scripts', True)

    project.set_property("copy_resources_target", "$dir_dist")
    project.get_property("copy_resources_glob").append("LICENSE")
    project.get_property("filter_resources_glob").append("**/pybuilder/__init__.py")

    project.get_property("source_dist_ignore_patterns").append(".project")
    project.get_property("source_dist_ignore_patterns").append(".pydevproject")
    project.get_property("source_dist_ignore_patterns").append(".settings")

    # enable this to build a bdist on vagrant
    # project.set_property("distutils_issue8876_workaround_enabled", True)
    project.get_property("distutils_commands").append("bdist_wheel")
    project.set_property("distutils_console_scripts", ["pyb_ = pybuilder.cli:main"])
    project.set_property("distutils_classifiers", [
                         'Programming Language :: Python',
                         'Programming Language :: Python :: Implementation :: CPython',
                         'Programming Language :: Python :: Implementation :: PyPy',
                         'Programming Language :: Python :: 2.6',
                         'Programming Language :: Python :: 2.7',
                         'Programming Language :: Python :: 3',
                         'Programming Language :: Python :: 3.2',
                         'Programming Language :: Python :: 3.3',
                         'Programming Language :: Python :: 3.4',
                         'Development Status :: 4 - Beta',
                         'Environment :: Console',
                         'Intended Audience :: Developers',
                         'License :: OSI Approved :: Apache Software License',
                         'Topic :: Software Development :: Build Tools',
                         'Topic :: Software Development :: Quality Assurance',
                         'Topic :: Software Development :: Testing'])
<|endoftext|>


<commit_before>import pytest
import hypothesis
import hypothesis.strategies as strategies
from testix import scenario
from testix import testixexception
from testix import expectations
from testix import hook
from testix import fake
from testix import DSL

class TestScenario:
    def test_EmptyScenario( self ):
        with scenario.Scenario() as s:
            pass

    def test_OnlyOneScenarioMayExistAtAnyOneTime( self ):
        with scenario.Scenario() as s:
            with pytest.raises( testixexception.TestixError ):
                scenario.Scenario()

    def test_TwoScenariosOneAfterTheOther( self ):
        with scenario.Scenario() as s:
            pass
        with scenario.Scenario() as s:
            pass

    @hypothesis.given(A=strategies.integers(),B=strategies.integers())
    def test_CallExpectationReturnsFakeValue(self, A, B):
        with scenario.Scenario() as s:
            s << expectations.Call( 'some_object', A ).returns( B )
            fakeObject = fake.Fake('some_object')
            assert fakeObject( A ) == B

    @hypothesis.given(A=strategies.integers(),B=strategies.integers(),C=strategies.integers(),D=strategies.integers(),E=strategies.integers())
    def test_TwoFakeCallsGetCorrectValues(self, A, B, C, D, E):
        with scenario.Scenario() as s:
            s.some_object( A ) >> B
            s.another_object( C, D ) >> E
            some_object = fake.Fake('some_object')
            another_object = fake.Fake('another_object')
            assert some_object( A ) == B
            assert another_object( C, D ) == E

    def test_TwoFakeCalls_MustBeInOrder( self ):
        class PreventScenarioEndVerifications(Exception): pass
        with pytest.raises(PreventScenarioEndVerifications):
            with scenario.Scenario() as s:
                s.some_object( 10 ).returns( 15 )
                s.another_object( 20, 50 ).returns( 30 )
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                with pytest.raises( testixexception.ExpectationException ):
                    another_object( 20, 50 )

                raise PreventScenarioEndVerifications()

    def test_Four_FakeCalls_MustBeInOrder( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ) >> 15
            s.another_object( 20, 50 ).returns( 30 )
            s.some_object( 'x' ).returns( 'y' )
            s.another_object( 'X', 'Y' ) >> 'Z'
            some_object = fake.Fake('some_object')
            another_object = fake.Fake('another_object')
            assert some_object( 10 ) == 15
            assert another_object( 20, 50 ) == 30
            assert some_object( 'x' ) == 'y'
            assert another_object( 'X', 'Y' ) == 'Z'

    def test_ScenarioEndsPrematurely( self ):
        with pytest.raises( testixexception.ScenarioException ):
            with scenario.Scenario() as s:
                s.some_object( 10 ).returns( 15 )
                s.another_object( 20, 50 ).returns( 30 )
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                assert some_object( 10 ) == 15

    def test_bugfix_ScenarioEndsPrematurely_With_UnorderedCalls( self ):
        with pytest.raises( testixexception.ScenarioException ):
            with scenario.Scenario() as s:
                s.some_object( 10 )
                s.another_object( 20, 50 ).unordered()
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                some_object( 10 )

    def test_CallParametersDontMatch( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).returns( 15 )
            some_object = fake.Fake('some_object')
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 1024 )

    def test_ShiftLeftOperator( self ):
        with scenario.Scenario() as s:
            s <<\
                expectations.Call( 'some_object', 10 ).returns( 15 ) <<\
                expectations.Call( 'some_object', 15 ).returns( 30 )
            some_object = fake.Fake('some_object')
            assert some_object( 10 ) == 15
            assert some_object( 15 ) == 30

    def test_ThrowingCallExpectation( self ):
        class MyException( Exception ): pass

        with scenario.Scenario() as s:
            s.some_object( 10 ).throwing( MyException )
            some_object = fake.Fake('some_object')
            with pytest.raises( MyException ):
                some_object( 10 )

    def test_ThrowingCallExpectation_AlternateSyntax( self ):
        class MyException( Exception ): pass

        with scenario.Scenario() as s:
            s.some_object( 10 ) >> DSL.Throwing( MyException )
            some_object = fake.Fake('some_object')
            with pytest.raises( MyException ):
                some_object( 10 )

    @hypothesis.given( values=strategies.permutations( [ 10, 11, 12 ] ) )
    def test_UnorderedExpectation( self, values ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered()
            s.some_object( 11 ).unordered()
            s.some_object( 12 ).unordered()

            some_object = fake.Fake('some_object')
            some_object( values[ 0 ] )
            some_object( values[ 1 ] )
            some_object( values[ 2 ] )

    def test_UnorderedExpectationsRunOut( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered()
            s.some_object( 11 ).unordered()

            some_object = fake.Fake('some_object')
            some_object( 11 )
            some_object( 10 )
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 11 )

    def test_EverlastingCall( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered().everlasting()
            s.some_object( 11 ).unordered().everlasting()
            some_object = fake.Fake('some_object')
            some_object( 10 )
            some_object( 10 )
            some_object( 10 )
            some_object( 10 )
            some_object( 11 )
            some_object( 11 )

    def test_Everlasting_Unorderd_and_Regular_Calls( self ):
        with scenario.Scenario() as s:
            s.everlasting( 10 ).returns( 'ten' ).unordered().everlasting()
            s.everlasting( 11 ).returns( 'eleven' ).unordered().everlasting()
            s.unordered( 20 ).returns( 'twenty' ).unordered()
            s.unordered( 19 ).returns( 'nineteen' ).unordered()
            s.ordered( 1 ).returns( 'one' )
            s.ordered( 2 ).returns( 'two' )
            s.ordered( 3 ).returns( 'three' )

            ordered = fake.Fake('ordered')
            everlasting = fake.Fake('everlasting')
            unordered = fake.Fake('unordered')

            assert everlasting( 10 ) == 'ten'
            assert ordered( 1 ) == 'one'
            assert ordered( 2 ) == 'two'
            assert everlasting( 10 ) == 'ten'
            assert everlasting( 11 ) == 'eleven'
            assert everlasting( 11 ) == 'eleven'
            assert everlasting( 10 ) == 'ten'
            assert ordered( 3 ) == 'three'
            assert everlasting( 11 ) == 'eleven'
            assert unordered( 20 ) == 'twenty'
            assert everlasting( 10 ) == 'ten'
            assert unordered( 19 ) == 'nineteen'
            assert everlasting( 10 ) == 'ten'

    def test_Everlasting_Calls_Have_ArgumentExpectations( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).returns( 'ten' ).unordered().everlasting()

            some_object = fake.Fake('some_object')
            assert some_object( 10 ) == 'ten'
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 11 )

    def test_Hooks( self ):
        func1Calls = []
        def func1( * a, **k ):
                func1Calls.append( ( a, k ) )

        with scenario.Scenario() as s:
            s.some_object( 10 )
            s << hook.Hook( func1, 10, 20, name = 'Moshe' )
            s << hook.Hook( func1, 70, 80, name = 'Avraham' )
            s.some_object( 11 )
            s << hook.Hook( func1, 11, 21, name = 'Haim' )

            some_object = fake.Fake('some_object')
            some_object( 10 )
            assert len( func1Calls ) == 2
            assert func1Calls[ 0 ] == ( ( 10, 20 ), { 'name': 'Moshe' } )
            assert func1Calls[ 1 ] == ( ( 70, 80 ), { 'name': 'Avraham' } )
            some_object( 11 )
            assert len( func1Calls ) == 3
            func1Calls[ 2 ] == ( 11, 21 ), { 'name': 'Haim' }

    def test_fake_context(self):
        locker_mock = fake.Fake('locker')
        with scenario.Scenario() as s:
            s.__with__.locker.Lock() >> fake.Fake('locked')
            s.locked.read() >> 'value'
            s.locked.updater.go('another_value')

            with locker_mock.Lock() as locked:
                assert locked.read() == 'value'
                locked.updater.go('another_value')

    def test_anonymous_fake_context(self):
        locker_mock = fake.Fake('locker')
        with scenario.Scenario() as s:
            s.__with__.locker.Lock()

            with locker_mock.Lock():
                pass

    def test_enforce_use_of_with_statement_with_context_manager_expectation(self):
        locker_mock = fake.Fake('locker')
        with pytest.raises(testixexception.ScenarioException, match='locker.Lock.*__enter__'):
            with scenario.Scenario() as s:
                s.__with__.locker.Lock()

                locker_mock.Lock()

    def test_fake_context_returns_arbitrary_value(self):
        tempfile_mock = fake.Fake('tempfile')
        read_mock = fake.Fake('read')
        with scenario.Scenario() as s:
            s.__with__.tempfile.TemporaryDirectory() >> '/path/to/dir'
            s.read('/path/to/dir')

            with tempfile_mock.TemporaryDirectory() as folder:
                read_mock(folder)

    def test_dynamic_fake_names(self):
        with scenario.Scenario() as s:
            s.__dynamic__('some_object')(33) >> 44
            fakeObject = fake.Fake('some_object')
            assert fakeObject(33) == 44

    def test_expectation_from_fake_objects(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            s.__from_fake__(fakeObject)(33) >> 44
            assert fakeObject(33) == 44

    def test_fix_issue_27__path_attribute_is_possible(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object', path='/path/to/nowhere')
            s.some_object.what() >> 'where'

            assert fakeObject.what() == 'where'
            assert fakeObject.path == '/path/to/nowhere'

    def test_scenario_resets_attributes_on_fakes(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            fake.Fake('some_object').name = 'haim'
            fake.Fake('some_object').age = 40
            assert fakeObject.age == 40
            assert fakeObject.name == 'haim'

        with scenario.Scenario() as s:
            fake.Fake('some_object').height = 180
            assert fake.Fake('some_object').height == 180
            assert type(fakeObject.age) is fake.Fake
            assert type(fakeObject.haim) is fake.Fake

        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            assert type(fakeObject.height) is fake.Fake
            assert type(fakeObject.age) is fake.Fake
            assert type(fakeObject.haim) is fake.Fake

    @pytest.mark.asyncio
    async def test_async_expectations(self):
        with scenario.Scenario('awaitable test') as s:
            fakeObject = fake.Fake('some_object')
            s.__await_on__.some_object('wtf') >> fake.Fake('another')
            s.another() >> 555
            s.__await_on__.another() >> fake.Fake('yet_another')
            s.__await_on__.yet_another() >> 777

            another = await fakeObject('wtf')
            assert another() == 555
            yet_another = await another()
            assert await yet_another() == 777

        with scenario.Scenario('awaitable chain test') as s:
            fakeObject = fake.Fake('some_object')
            s.__await_on__.some_object.some_attribute.another_method('wtf') >> 777
            assert await fakeObject.some_attribute.another_method('wtf') == 777

        with scenario.Scenario('awaitable throws') as s:
            class MyException( Exception ): pass
            s.__await_on__.some_object( 10 ) >> DSL.Throwing( MyException )
            with pytest.raises( MyException ):
                await fakeObject( 10 )

    @pytest.mark.asyncio
    async def test_async_context_managers(self):
        with scenario.Scenario('async context managers') as s:
            s.__async_with__.open('/path/to/file', 'rw') >> fake.Fake('my_file')
            s.__await_on__.my_file.read(500) >> 'some text'
            s.my_file.seek(0)
            s.__await_on__.my_file.write('more text') >> 10

            open_mock = fake.Fake('open')
            async with open_mock('/path/to/file', 'rw') as my_file:
                assert await my_file.read(500) == 'some text'
                my_file.seek(0)
                assert await my_file.write('more text') == 10
<commit_msg>add some tests<commit_after>import pytest
import hypothesis
import hypothesis.strategies as strategies
from testix import scenario
from testix import testixexception
from testix import expectations
from testix import hook
from testix import fake
from testix import DSL

class TestScenario:
    def test_EmptyScenario( self ):
        with scenario.Scenario() as s:
            pass

    def test_OnlyOneScenarioMayExistAtAnyOneTime( self ):
        with scenario.Scenario() as s:
            with pytest.raises( testixexception.TestixError ):
                scenario.Scenario()

    def test_TwoScenariosOneAfterTheOther( self ):
        with scenario.Scenario() as s:
            pass
        with scenario.Scenario() as s:
            pass

    @hypothesis.given(A=strategies.integers(),B=strategies.integers())
    def test_CallExpectationReturnsFakeValue(self, A, B):
        with scenario.Scenario() as s:
            s << expectations.Call( 'some_object', A ).returns( B )
            fakeObject = fake.Fake('some_object')
            assert fakeObject( A ) == B

    @hypothesis.given(A=strategies.integers(),B=strategies.integers(),C=strategies.integers(),D=strategies.integers(),E=strategies.integers())
    def test_TwoFakeCallsGetCorrectValues(self, A, B, C, D, E):
        with scenario.Scenario() as s:
            s.some_object( A ) >> B
            s.another_object( C, D ) >> E
            some_object = fake.Fake('some_object')
            another_object = fake.Fake('another_object')
            assert some_object( A ) == B
            assert another_object( C, D ) == E

    def test_TwoFakeCalls_MustBeInOrder( self ):
        class PreventScenarioEndVerifications(Exception): pass
        with pytest.raises(PreventScenarioEndVerifications):
            with scenario.Scenario() as s:
                s.some_object( 10 ).returns( 15 )
                s.another_object( 20, 50 ).returns( 30 )
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                with pytest.raises( testixexception.ExpectationException ):
                    another_object( 20, 50 )

                raise PreventScenarioEndVerifications()

    def test_Four_FakeCalls_MustBeInOrder( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ) >> 15
            s.another_object( 20, 50 ).returns( 30 )
            s.some_object( 'x' ).returns( 'y' )
            s.another_object( 'X', 'Y' ) >> 'Z'
            some_object = fake.Fake('some_object')
            another_object = fake.Fake('another_object')
            assert some_object( 10 ) == 15
            assert another_object( 20, 50 ) == 30
            assert some_object( 'x' ) == 'y'
            assert another_object( 'X', 'Y' ) == 'Z'

    def test_ScenarioEndsPrematurely( self ):
        with pytest.raises( testixexception.ScenarioException ):
            with scenario.Scenario() as s:
                s.some_object( 10 ).returns( 15 )
                s.another_object( 20, 50 ).returns( 30 )
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                assert some_object( 10 ) == 15

    def test_bugfix_ScenarioEndsPrematurely_With_UnorderedCalls( self ):
        with pytest.raises( testixexception.ScenarioException ):
            with scenario.Scenario() as s:
                s.some_object( 10 )
                s.another_object( 20, 50 ).unordered()
                some_object = fake.Fake('some_object')
                another_object = fake.Fake('another_object')
                some_object( 10 )

    def test_CallParametersDontMatch( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).returns( 15 )
            some_object = fake.Fake('some_object')
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 1024 )

    def test_ShiftLeftOperator( self ):
        with scenario.Scenario() as s:
            s <<\
                expectations.Call( 'some_object', 10 ).returns( 15 ) <<\
                expectations.Call( 'some_object', 15 ).returns( 30 )
            some_object = fake.Fake('some_object')
            assert some_object( 10 ) == 15
            assert some_object( 15 ) == 30

    def test_ThrowingCallExpectation( self ):
        class MyException( Exception ): pass

        with scenario.Scenario() as s:
            s.some_object( 10 ).throwing( MyException )
            some_object = fake.Fake('some_object')
            with pytest.raises( MyException ):
                some_object( 10 )

    def test_ThrowingCallExpectation_AlternateSyntax( self ):
        class MyException( Exception ): pass

        with scenario.Scenario() as s:
            s.some_object( 10 ) >> DSL.Throwing( MyException )
            some_object = fake.Fake('some_object')
            with pytest.raises( MyException ):
                some_object( 10 )

    @hypothesis.given( values=strategies.permutations( [ 10, 11, 12 ] ) )
    def test_UnorderedExpectation( self, values ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered()
            s.some_object( 11 ).unordered()
            s.some_object( 12 ).unordered()

            some_object = fake.Fake('some_object')
            some_object( values[ 0 ] )
            some_object( values[ 1 ] )
            some_object( values[ 2 ] )

    def test_UnorderedExpectationsRunOut( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered()
            s.some_object( 11 ).unordered()

            some_object = fake.Fake('some_object')
            some_object( 11 )
            some_object( 10 )
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 11 )

    def test_EverlastingCall( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).unordered().everlasting()
            s.some_object( 11 ).unordered().everlasting()
            some_object = fake.Fake('some_object')
            some_object( 10 )
            some_object( 10 )
            some_object( 10 )
            some_object( 10 )
            some_object( 11 )
            some_object( 11 )

    def test_Everlasting_Unorderd_and_Regular_Calls( self ):
        with scenario.Scenario() as s:
            s.everlasting( 10 ).returns( 'ten' ).unordered().everlasting()
            s.everlasting( 11 ).returns( 'eleven' ).unordered().everlasting()
            s.unordered( 20 ).returns( 'twenty' ).unordered()
            s.unordered( 19 ).returns( 'nineteen' ).unordered()
            s.ordered( 1 ).returns( 'one' )
            s.ordered( 2 ).returns( 'two' )
            s.ordered( 3 ).returns( 'three' )

            ordered = fake.Fake('ordered')
            everlasting = fake.Fake('everlasting')
            unordered = fake.Fake('unordered')

            assert everlasting( 10 ) == 'ten'
            assert ordered( 1 ) == 'one'
            assert ordered( 2 ) == 'two'
            assert everlasting( 10 ) == 'ten'
            assert everlasting( 11 ) == 'eleven'
            assert everlasting( 11 ) == 'eleven'
            assert everlasting( 10 ) == 'ten'
            assert ordered( 3 ) == 'three'
            assert everlasting( 11 ) == 'eleven'
            assert unordered( 20 ) == 'twenty'
            assert everlasting( 10 ) == 'ten'
            assert unordered( 19 ) == 'nineteen'
            assert everlasting( 10 ) == 'ten'

    def test_Everlasting_Calls_Have_ArgumentExpectations( self ):
        with scenario.Scenario() as s:
            s.some_object( 10 ).returns( 'ten' ).unordered().everlasting()

            some_object = fake.Fake('some_object')
            assert some_object( 10 ) == 'ten'
            with pytest.raises( testixexception.ExpectationException ):
                some_object( 11 )

    def test_Hooks( self ):
        func1Calls = []
        def func1( * a, **k ):
                func1Calls.append( ( a, k ) )

        with scenario.Scenario() as s:
            s.some_object( 10 )
            s << hook.Hook( func1, 10, 20, name = 'Moshe' )
            s << hook.Hook( func1, 70, 80, name = 'Avraham' )
            s.some_object( 11 )
            s << hook.Hook( func1, 11, 21, name = 'Haim' )

            some_object = fake.Fake('some_object')
            some_object( 10 )
            assert len( func1Calls ) == 2
            assert func1Calls[ 0 ] == ( ( 10, 20 ), { 'name': 'Moshe' } )
            assert func1Calls[ 1 ] == ( ( 70, 80 ), { 'name': 'Avraham' } )
            some_object( 11 )
            assert len( func1Calls ) == 3
            func1Calls[ 2 ] == ( 11, 21 ), { 'name': 'Haim' }

    def test_fake_context(self):
        locker_mock = fake.Fake('locker')
        with scenario.Scenario() as s:
            s.__with__.locker.Lock() >> fake.Fake('locked')
            s.locked.read() >> 'value'
            s.locked.updater.go('another_value')

            with locker_mock.Lock() as locked:
                assert locked.read() == 'value'
                locked.updater.go('another_value')

    def test_anonymous_fake_context(self):
        locker_mock = fake.Fake('locker')
        with scenario.Scenario() as s:
            s.__with__.locker.Lock()

            with locker_mock.Lock():
                pass

    def test_enforce_use_of_with_statement_with_context_manager_expectation(self):
        locker_mock = fake.Fake('locker')
        with pytest.raises(testixexception.ScenarioException, match='locker.Lock.*__enter__'):
            with scenario.Scenario() as s:
                s.__with__.locker.Lock()

                locker_mock.Lock()

    def test_fake_context_returns_arbitrary_value(self):
        tempfile_mock = fake.Fake('tempfile')
        read_mock = fake.Fake('read')
        with scenario.Scenario() as s:
            s.__with__.tempfile.TemporaryDirectory() >> '/path/to/dir'
            s.read('/path/to/dir')

            with tempfile_mock.TemporaryDirectory() as folder:
                read_mock(folder)

    def test_dynamic_fake_names(self):
        with scenario.Scenario() as s:
            s.__dynamic__('some_object')(33) >> 44
            fakeObject = fake.Fake('some_object')
            assert fakeObject(33) == 44

    def test_expectation_from_fake_objects(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            s.__from_fake__(fakeObject)(33) >> 44
            assert fakeObject(33) == 44

    def test_fix_issue_27__path_attribute_is_possible(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object', path='/path/to/nowhere')
            s.some_object.what() >> 'where'

            assert fakeObject.what() == 'where'
            assert fakeObject.path == '/path/to/nowhere'

    def test_scenario_resets_attributes_on_fakes(self):
        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            fake.Fake('some_object').name = 'haim'
            fake.Fake('some_object').age = 40
            assert fakeObject.age == 40
            assert fakeObject.name == 'haim'

        with scenario.Scenario() as s:
            fake.Fake('some_object').height = 180
            assert fake.Fake('some_object').height == 180
            assert type(fakeObject.age) is fake.Fake
            assert type(fakeObject.haim) is fake.Fake

        with scenario.Scenario() as s:
            fakeObject = fake.Fake('some_object')
            assert type(fakeObject.height) is fake.Fake
            assert type(fakeObject.age) is fake.Fake
            assert type(fakeObject.haim) is fake.Fake

    @pytest.mark.asyncio
    async def test_async_expectations(self):
        with scenario.Scenario('awaitable test') as s:
            fakeObject = fake.Fake('some_object')
            s.__await_on__.some_object('wtf') >> fake.Fake('another')
            s.another() >> 555
            s.__await_on__.another() >> fake.Fake('yet_another')
            s.__await_on__.yet_another() >> 777

            another = await fakeObject('wtf')
            assert another() == 555
            yet_another = await another()
            assert await yet_another() == 777

        with scenario.Scenario('awaitable chain test') as s:
            fakeObject = fake.Fake('some_object')
            s.__await_on__.some_object.some_attribute.another_method('wtf') >> 777
            assert await fakeObject.some_attribute.another_method('wtf') == 777

        with scenario.Scenario('awaitable throws') as s:
            class MyException( Exception ): pass
            s.__await_on__.some_object( 10 ) >> DSL.Throwing( MyException )
            with pytest.raises( MyException ):
                await fakeObject( 10 )

    @pytest.mark.asyncio
    async def test_async_context_managers(self):
        with scenario.Scenario() as s:
            s.__async_with__.open('/path/to/file', 'rw') >> fake.Fake('my_file')
            s.__await_on__.my_file.read(500) >> 'some text'
            s.my_file.seek(0)
            s.__await_on__.my_file.write('more text') >> 10

            open_mock = fake.Fake('open')
            async with open_mock('/path/to/file', 'rw') as my_file:
                assert await my_file.read(500) == 'some text'
                my_file.seek(0)
                assert await my_file.write('more text') == 10

    @pytest.mark.asyncio
    async def test_async_anonymous_context_managers(self):
        my_file = fake.Fake('my_file')
        with scenario.Scenario() as s:
            s.__async_with__.locker.lock()
            s.__await_on__.my_file.read(500) >> 'some text'

            locker_mock = fake.Fake('locker')

            async with locker_mock.lock():
                assert await my_file.read(500) == 'some text'

    def test_enforce_use_of_with_statement_with_async_context_manager_expectation(self):
        locker_mock = fake.Fake('locker')
        with pytest.raises(testixexception.ScenarioException, match='locker.Lock.*__aenter__'):
            with scenario.Scenario() as s:
                s.__async_with__.locker.Lock()

                locker_mock.Lock()
<|endoftext|>