<commit_before>from flask import render_template, request

from server.mod_auth.auth import login

def define_routes(app):
    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/user/login')
    def route_login():
        return login(request)

    @app.route('/statics/<path:path>')
    def handle_test(path):
        return render_template('index.html')

    # Serve Static Assets
    # TODO: Do this with apache or nginx
    @app.route('/static/<path:file_path>.<extension>')
    def static_proxy(file_path, extension):
        file_path = file_path.rstrip('/') + "." + extension
        app.logger.info('File Path: %s' % file_path)
        return app.send_static_file(file_path)
<commit_msg>Remove unused route<commit_after>from flask import render_template, request

from server.mod_auth.auth import login

def define_routes(app):
    @app.route('/')
    def index():
        return render_template('index.html')

    @app.route('/user/login')
    def route_login():
        return login(request)

    # Serve Static Assets
    # TODO: Do this with apache or nginx
    @app.route('/static/<path:file_path>.<extension>')
    def static_proxy(file_path, extension):
        file_path = file_path.rstrip('/') + "." + extension
        app.logger.info('File Path: %s' % file_path)
        return app.send_static_file(file_path)
<|endoftext|>


<commit_before>"""
To contain language-related ops.
"""
from collections import OrderedDict
import babel
from babel import Locale, UnknownLocaleError
from appcomposer.i18n import gettext
from flask import request

def obtain_groups():
    """
    Obtains the groups that are available for translation, as an Ordered Dictionary.

    :return: Ordered dictionary with the name of the groups identified by each key.
    :rtype: OrderedDict
    """
    groups = OrderedDict()
    groups["ALL"] = "ALL"
    groups["10-13"] = gettext("Preadolescence (age 10-13)")
    groups["14-18"] = gettext("Adolescence (age 14-18)")
    return groups

# Taken from http://en.wikipedia.org/wiki/Languages_of_the_European_Union, April 2015
OFFICIAL_EUROPEAN_UNION_LANGUAGES = ['bg', 'hr', 'cs', 'da', 'nl', 'en', 'et', 'fi', 'fr', 'de', 'el', 'hu', 'ga', 'it', 'lv', 'lt', 'mt', 'pl', 'pt', 'ro', 'sk', 'sl', 'es', 'sv']
SEMIOFFICIAL_EUROPEAN_UNION_LANGUAGES = ['eu', 'ca', 'gl', 'gd', 'cy']
OTHER_LANGUAGES = [
    # The following languages are in Graasp
    'uk', # Ukranian
    'tr', # Turkish
    'sr', # Serbian language
    'ru', # Russian language
    'be', # Belarussian
    # The following languages are too widely used
    'ar', # Arabic
    'zh', # Chinese
    'hi', # Hindi
    # The following were available in the Go-Lab portal
    'bs', # Bosnian
    'sh', # Serbo-Croatian,
    'lb', # Luxembourgish,
    'se', # Northern Sami
    # The following have been selected to be interesting for Go-Lab
    'no', # Norwegian
    'id', # Indonesian
    'ja', # Japanese
    'my', # Burmese
    'mk', # Macedonian
    'he', # Hebrew
    'sw', # Swahili
    'vi', # Vietnamese
    'zh_TW', # Taiwanese
    'ka', # Georgian
    'kk', # Kazakh
    'ky', # Kyrgyz
    'tg', # Tajik
]

ALL_LANGUAGES = OFFICIAL_EUROPEAN_UNION_LANGUAGES + SEMIOFFICIAL_EUROPEAN_UNION_LANGUAGES + OTHER_LANGUAGES

def obtain_languages():
    """
    Obtains the languages (without the groups) that are available for translation,
    as a Dictionary. The format is code:language_name

    TO-DO: This method can probably be optimized.

    :return:
    """
    babel_supported_languages = babel.core.Locale("en", "US").languages.items()
    languages = []
    for code, lang in babel_supported_languages:
        golab_supported = False
        for supported_code in ALL_LANGUAGES:
            if code == supported_code:
                golab_supported = True
                break
        if golab_supported:
            languages.append( (code, lang) )

    languages.append( ('zh_TW', 'Chinese (Traditional)') )

    if False:
        print "Babel Supported languages after filter: %s" % len(languages)
        print "Go-Lab Supported languages: %s" % len(ALL_LANGUAGES)
    languages.sort(key=lambda it: it[1])

    # TODO: Currently, we filter languages which contain "_" in their code so as to simplify.
    # Because we use _ throughout the composer as a separator character, trouble is caused otherwise.
    # Eventually we should consider whether we need to support special languages with _
    # on its code.
    targetlangs_codes = [lang[0] + "_ALL" for lang in languages if "_" not in lang[0]]
    for code, name in languages:
        if '_' in code and code.count('_') == 1:
            targetlangs_codes.append(code)

    targetlangs_list = [{"pcode": code, "repr": get_locale_english_name(
        *get_locale_info_from_code(code))} for code in targetlangs_codes]

    d = {lang["pcode"]: lang["repr"] for lang in targetlangs_list}
    d["all_ALL"] = "DEFAULT"
    return d

def get_locale_info_from_code(code):
    """
    Retrieves the lang, country and group from a full or partial locale code.
    @param code: Locale code. It can be a full code (ca_ES_ALL) or partial code (ca_ES).
    @return: (lang, country, group) or (lang, country), depending if it's full or partial.
    """
    splits = code.split("_")

    # If our code is only "ca_ES" style (doesn't include group).
    if len(splits) == 2:
        lang, country = splits
        return lang, country

    # If we have 3 splits then it is probably "ca_ES_ALL" style (includes group).
    elif len(splits) == 3:
        lang, country, group = splits
        return lang, country, group

    # Unknown number of splits. Throw an exception, it is not a recognized code.
    else:
        raise UnrecognizedLocaleCodeException("The locale code can't be recognized: " + code)

def get_locale_english_name(lang, country):
    """
    Retrieves a string representation of a Locale.
    @param lang: Lang code.
    @param country: Country code.
    @return: String representation for the locale.
    """
    if lang == 'mk':
        return u'Macedonian Slavic'
    if lang == 'zh' and country == 'TW':
        return u'Chinese (Traditional)'
    if lang == 'zh' and country in ('ALL', 'CN'):
        return u'Chinese (Simplified)'

    try:
        if country.upper() == 'ALL':
            country = ""
        return Locale(lang, country).english_name
    except UnknownLocaleError:
        return Locale("en", "US").languages.get(lang)

class UnrecognizedLocaleCodeException(Exception):
    """
    Exception thrown when the format of a locale code does not seem to be
    as expected.
    """

LANGUAGES = obtain_languages()
# This is a dictionary like { 'English' : 'en', 'French' : 'fr' ...}
LANGUAGES_PER_NAME = { v: k for k, v in babel.Locale('en').languages.items() }
LANGUAGE_NAMES_PER_CODE = { k: v for k, v in babel.Locale('en').languages.items() }
LANGUAGES_ORDER = (
                # Official languages
                ['English', 'German', 'French', 'Italian', 'Spanish', 'Polish', 'Romanian', 'Dutch', 'Hungarian', 'Portuguese', 'Greek', 'Swedish', 'Czech', 'Bulgarian', 'Slovak', 'Danish', 'Finnish', 'Lithuanian', 'Slovene', 'Slovenian', 'Estonian', 'Croatian', 'Irish', 'Latvian', 'Maltese']
                # Semi-official languages
                + ['Catalan', 'Galician', 'Basque', 'Scottish Gaelic', 'Luxembourgish', 'Luxembourgeois', 'Welsh']
                # + Most used foreign languages
                + ['Russian', 'Arabic', 'Turkish', 'Tamil', 'Chinese', 'Japanese', 'Korean', 'Hindi', 'Urdu']
        )

# Sometimes in golabz some languages are displayed in a format not supported by babel
# Here is a translation for those known issues
WRONG_LANGUAGES = {
    'Serbo Croatian' : 'Serbo-Croatian',
    'Luxembourgeois' : 'Luxembourgish',
    'Slovene': 'Slovenian',
    'Macedonian': 'Macedonian Slavic',
}

WRONG_LANGUAGES_PER_CORRECT_NAME = {}
for wrong_name, correct_name in WRONG_LANGUAGES.items():
    if correct_name in WRONG_LANGUAGES_PER_CORRECT_NAME:
        WRONG_LANGUAGES_PER_CORRECT_NAME[correct_name].append(wrong_name)
    else:
        WRONG_LANGUAGES_PER_CORRECT_NAME[correct_name] = [ wrong_name ]

# Given this percentage, the AppComposer will decide whether to report if an app has been updated or not.
LANGUAGE_THRESHOLD = 0.8

def sort_languages(languages):
    """
    Given a list of languages in English; e.g.: [ 'Spanish', 'Welsh', 'English']
    sort the list of languages by population speaking it according to:

    https://en.wikipedia.org/wiki/Languages_of_the_European_Union#Knowledge

    and return such list.
    """
    old_languages = list(languages)
    new_languages = []
    # sorted as suggested in Wikipedia
    for lang in LANGUAGES_ORDER:
        if lang in old_languages:
            old_languages.remove(lang)
            new_languages.append(lang)

    new_languages.extend(sorted(old_languages))

    return new_languages

def guess_default_language():
    best_match = request.accept_languages.best_match([ lang_code.split('_')[0] for lang_code in LANGUAGES ])
    default_language = None
    if best_match is not None:
        if best_match in LANGUAGES:
            default_language = best_match
        else:
            lang_codes = [ lang_code for lang_code in LANGUAGES if lang_code.startswith('%s_' % best_match) ]
            if lang_codes:
                default_language = lang_codes[0]
    return default_language

<commit_msg>Add Persian<commit_after>"""
To contain language-related ops.
"""
from collections import OrderedDict
import babel
from babel import Locale, UnknownLocaleError
from appcomposer.i18n import gettext
from flask import request

def obtain_groups():
    """
    Obtains the groups that are available for translation, as an Ordered Dictionary.

    :return: Ordered dictionary with the name of the groups identified by each key.
    :rtype: OrderedDict
    """
    groups = OrderedDict()
    groups["ALL"] = "ALL"
    groups["10-13"] = gettext("Preadolescence (age 10-13)")
    groups["14-18"] = gettext("Adolescence (age 14-18)")
    return groups

# Taken from http://en.wikipedia.org/wiki/Languages_of_the_European_Union, April 2015
OFFICIAL_EUROPEAN_UNION_LANGUAGES = ['bg', 'hr', 'cs', 'da', 'nl', 'en', 'et', 'fi', 'fr', 'de', 'el', 'hu', 'ga', 'it', 'lv', 'lt', 'mt', 'pl', 'pt', 'ro', 'sk', 'sl', 'es', 'sv']
SEMIOFFICIAL_EUROPEAN_UNION_LANGUAGES = ['eu', 'ca', 'gl', 'gd', 'cy']
OTHER_LANGUAGES = [
    # The following languages are in Graasp
    'uk', # Ukranian
    'tr', # Turkish
    'sr', # Serbian language
    'ru', # Russian language
    'be', # Belarussian
    # The following languages are too widely used
    'ar', # Arabic
    'zh', # Chinese
    'hi', # Hindi
    # The following were available in the Go-Lab portal
    'bs', # Bosnian
    'sh', # Serbo-Croatian,
    'lb', # Luxembourgish,
    'se', # Northern Sami
    # The following have been selected to be interesting for Go-Lab
    'no', # Norwegian
    'id', # Indonesian
    'ja', # Japanese
    'my', # Burmese
    'mk', # Macedonian
    'he', # Hebrew
    'sw', # Swahili
    'vi', # Vietnamese
    'zh_TW', # Taiwanese
    'ka', # Georgian
    'kk', # Kazakh
    'ky', # Kyrgyz
    'tg', # Tajik
    'fa', # Persian / Farsi
]

ALL_LANGUAGES = OFFICIAL_EUROPEAN_UNION_LANGUAGES + SEMIOFFICIAL_EUROPEAN_UNION_LANGUAGES + OTHER_LANGUAGES

def obtain_languages():
    """
    Obtains the languages (without the groups) that are available for translation,
    as a Dictionary. The format is code:language_name

    TO-DO: This method can probably be optimized.

    :return:
    """
    babel_supported_languages = babel.core.Locale("en", "US").languages.items()
    languages = []
    for code, lang in babel_supported_languages:
        golab_supported = False
        for supported_code in ALL_LANGUAGES:
            if code == supported_code:
                golab_supported = True
                break
        if golab_supported:
            languages.append( (code, lang) )

    languages.append( ('zh_TW', 'Chinese (Traditional)') )

    if False:
        print "Babel Supported languages after filter: %s" % len(languages)
        print "Go-Lab Supported languages: %s" % len(ALL_LANGUAGES)
    languages.sort(key=lambda it: it[1])

    # TODO: Currently, we filter languages which contain "_" in their code so as to simplify.
    # Because we use _ throughout the composer as a separator character, trouble is caused otherwise.
    # Eventually we should consider whether we need to support special languages with _
    # on its code.
    targetlangs_codes = [lang[0] + "_ALL" for lang in languages if "_" not in lang[0]]
    for code, name in languages:
        if '_' in code and code.count('_') == 1:
            targetlangs_codes.append(code)

    targetlangs_list = [{"pcode": code, "repr": get_locale_english_name(
        *get_locale_info_from_code(code))} for code in targetlangs_codes]

    d = {lang["pcode"]: lang["repr"] for lang in targetlangs_list}
    d["all_ALL"] = "DEFAULT"
    return d

def get_locale_info_from_code(code):
    """
    Retrieves the lang, country and group from a full or partial locale code.
    @param code: Locale code. It can be a full code (ca_ES_ALL) or partial code (ca_ES).
    @return: (lang, country, group) or (lang, country), depending if it's full or partial.
    """
    splits = code.split("_")

    # If our code is only "ca_ES" style (doesn't include group).
    if len(splits) == 2:
        lang, country = splits
        return lang, country

    # If we have 3 splits then it is probably "ca_ES_ALL" style (includes group).
    elif len(splits) == 3:
        lang, country, group = splits
        return lang, country, group

    # Unknown number of splits. Throw an exception, it is not a recognized code.
    else:
        raise UnrecognizedLocaleCodeException("The locale code can't be recognized: " + code)

def get_locale_english_name(lang, country):
    """
    Retrieves a string representation of a Locale.
    @param lang: Lang code.
    @param country: Country code.
    @return: String representation for the locale.
    """
    if lang == 'mk':
        return u'Macedonian Slavic'
    if lang == 'zh' and country == 'TW':
        return u'Chinese (Traditional)'
    if lang == 'zh' and country in ('ALL', 'CN'):
        return u'Chinese (Simplified)'

    try:
        if country.upper() == 'ALL':
            country = ""
        return Locale(lang, country).english_name
    except UnknownLocaleError:
        return Locale("en", "US").languages.get(lang)

class UnrecognizedLocaleCodeException(Exception):
    """
    Exception thrown when the format of a locale code does not seem to be
    as expected.
    """

LANGUAGES = obtain_languages()
# This is a dictionary like { 'English' : 'en', 'French' : 'fr' ...}
LANGUAGES_PER_NAME = { v: k for k, v in babel.Locale('en').languages.items() }
LANGUAGE_NAMES_PER_CODE = { k: v for k, v in babel.Locale('en').languages.items() }
LANGUAGES_ORDER = (
                # Official languages
                ['English', 'German', 'French', 'Italian', 'Spanish', 'Polish', 'Romanian', 'Dutch', 'Hungarian', 'Portuguese', 'Greek', 'Swedish', 'Czech', 'Bulgarian', 'Slovak', 'Danish', 'Finnish', 'Lithuanian', 'Slovene', 'Slovenian', 'Estonian', 'Croatian', 'Irish', 'Latvian', 'Maltese']
                # Semi-official languages
                + ['Catalan', 'Galician', 'Basque', 'Scottish Gaelic', 'Luxembourgish', 'Luxembourgeois', 'Welsh']
                # + Most used foreign languages
                + ['Russian', 'Arabic', 'Turkish', 'Tamil', 'Chinese', 'Japanese', 'Korean', 'Hindi', 'Urdu']
        )

# Sometimes in golabz some languages are displayed in a format not supported by babel
# Here is a translation for those known issues
WRONG_LANGUAGES = {
    'Serbo Croatian' : 'Serbo-Croatian',
    'Luxembourgeois' : 'Luxembourgish',
    'Slovene': 'Slovenian',
    'Macedonian': 'Macedonian Slavic',
}

WRONG_LANGUAGES_PER_CORRECT_NAME = {}
for wrong_name, correct_name in WRONG_LANGUAGES.items():
    if correct_name in WRONG_LANGUAGES_PER_CORRECT_NAME:
        WRONG_LANGUAGES_PER_CORRECT_NAME[correct_name].append(wrong_name)
    else:
        WRONG_LANGUAGES_PER_CORRECT_NAME[correct_name] = [ wrong_name ]

# Given this percentage, the AppComposer will decide whether to report if an app has been updated or not.
LANGUAGE_THRESHOLD = 0.8

def sort_languages(languages):
    """
    Given a list of languages in English; e.g.: [ 'Spanish', 'Welsh', 'English']
    sort the list of languages by population speaking it according to:

    https://en.wikipedia.org/wiki/Languages_of_the_European_Union#Knowledge

    and return such list.
    """
    old_languages = list(languages)
    new_languages = []
    # sorted as suggested in Wikipedia
    for lang in LANGUAGES_ORDER:
        if lang in old_languages:
            old_languages.remove(lang)
            new_languages.append(lang)

    new_languages.extend(sorted(old_languages))

    return new_languages

def guess_default_language():
    best_match = request.accept_languages.best_match([ lang_code.split('_')[0] for lang_code in LANGUAGES ])
    default_language = None
    if best_match is not None:
        if best_match in LANGUAGES:
            default_language = best_match
        else:
            lang_codes = [ lang_code for lang_code in LANGUAGES if lang_code.startswith('%s_' % best_match) ]
            if lang_codes:
                default_language = lang_codes[0]
    return default_language

<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import imghdr
import os

from rasa_core.evaluate import run_story_evaluation, \
    collect_story_predictions
from tests.conftest import DEFAULT_STORIES_FILE

def test_evaluation_image_creation(tmpdir, default_agent):
    model_path = os.path.join(tmpdir.strpath, "model")
    default_agent.persist(model_path)
    img_path = os.path.join(tmpdir.strpath, "evaltion.png")
    run_story_evaluation(
            story_file=DEFAULT_STORIES_FILE,
            policy_model_path=model_path,
            nlu_model_path=None,
            out_file=img_path,
            max_stories=None
    )

    assert os.path.isfile(img_path)
    assert imghdr.what(img_path) == "png"

def test_evaluation_script(tmpdir, default_agent):
    model_path = os.path.join(tmpdir.strpath, "model")
    default_agent.persist(model_path)
    actual, preds = collect_story_predictions(
            story_file=DEFAULT_STORIES_FILE,
            policy_model_path=model_path,
            nlu_model_path=None,
            max_stories=None,
            shuffle_stories=False
    )
    assert len(actual) == 14
    assert len(preds) == 14
<commit_msg>fix test<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import imghdr
import os

from rasa_core.evaluate import run_story_evaluation, \
    collect_story_predictions
from tests.conftest import DEFAULT_STORIES_FILE

def test_evaluation_image_creation(tmpdir, default_agent):
    model_path = os.path.join(tmpdir.strpath, "model")
    default_agent.persist(model_path)
    img_path = os.path.join(tmpdir.strpath, "evaluation.png")
    run_story_evaluation(
            resource_name=DEFAULT_STORIES_FILE,
            policy_model_path=model_path,
            nlu_model_path=None,
            out_file=img_path,
            max_stories=None
    )

    assert os.path.isfile(img_path)
    assert imghdr.what(img_path) == "png"

def test_evaluation_script(tmpdir, default_agent):
    model_path = os.path.join(tmpdir.strpath, "model")
    default_agent.persist(model_path)
    actual, preds = collect_story_predictions(
            story_file=DEFAULT_STORIES_FILE,
            policy_model_path=model_path,
            nlu_model_path=None,
            max_stories=None,
            shuffle_stories=False
    )
    assert len(actual) == 14
    assert len(preds) == 14
<|endoftext|>


<commit_before>"""
This module will hold the damage class in the game.
"""

class Damage:
    """ This class holds the damage of every character/monster in the game"""
    def __init__(self, phys_dmg: float=0, magic_dmg: float=0):
        self.phys_dmg = round(phys_dmg, 1)
        self.magic_dmg = round(magic_dmg, 1)
        self.phys_absorbed, self.magic_absorbed = 0, 0

    def __str__(self):
        """
        Have two separate strings for physical damage and magical damage.
        Fill them if we have such damages and modify them if there is absorption
        Then, return what's appropriate
        """
        phys_dmg_print = ""
        if self.phys_dmg:
            phys_dmg_print = f'{self.phys_dmg:.2f} physical damage'

        if self.phys_absorbed:
            phys_dmg_print = f'{self.phys_dmg:.2f} physical damage ({self.phys_absorbed:.2f} absorbed)'

        magic_dmg_print = ""
        if self.magic_dmg:
            magic_dmg_print = f'{sel.formatf.magic_dmg:.2f} magical damage'

        if self.magic_absorbed:
            magic_dmg_print = f'{self.magic_dmg:.2f} magical damage ({self.magic_absorbed:.2f} absorbed)'

        if phys_dmg_print and magic_dmg_print:
            return f'{phys_dmg_print} and {magic_dmg_print}'
        elif phys_dmg_print:
            return phys_dmg_print
        elif magic_dmg_print:
            return magic_dmg_print
        else:
            return "0 damage"

    def __sub__(self, other):
        return (self.phys_dmg + self.magic_dmg) - other

    def __rsub__(self, other):
        return other - (self.phys_dmg + self.magic_dmg)

    def __isub__(self, other: tuple):
        other_phys, other_magic = 0, 0  # type: int
        # unpack other damage
        if isinstance(other, tuple):
            other_phys, other_magic = other
        elif isinstance(other, Damage):
            other_phys = other.phys_dmg
            other_magic = other.magic_dmg

        # does not let the numbers get negative
        modified_phys_damage = max(self.phys_dmg - other_phys, 0)
        modified_magic_damage = max(self.magic_dmg - other_magic, 0)

        return Damage(phys_dmg=modified_phys_damage,
                      magic_dmg=modified_magic_damage)

    def __iadd__(self, other: tuple):
        other_phys, other_magic = 0, 0  # type: int
        # unpack other damage
        if isinstance(other, tuple):
            other_phys, other_magic = other
        elif isinstance(other, Damage):
            other_phys = other.phys_dmg
            other_magic = other.magic_dmg

        return Damage(phys_dmg=self.phys_dmg + other_phys,
                      magic_dmg=self.magic_dmg + other_magic)

    def __mul__(self, other: float):
        return Damage(phys_dmg=(other * self.phys_dmg),
                      magic_dmg=(other * self.magic_dmg))

    def handle_absorption(self, absorption_shield: float):
        """
        This method subtracts the absorbed damage from our damage
        The magical damage always gets absorbed first!
        :param absorption_shield: a float indicating how much damage should get absorbed
        :return: What's left of the absorption
        """

        # subtract magic damage
        if absorption_shield >= self.magic_dmg:
            # shield is bigger
            absorption_shield -= self.magic_dmg
            self.magic_absorbed = self.magic_dmg
            self.magic_dmg = 0

            # subtract physical damage
            if absorption_shield >= self.phys_dmg:
                # shield is bigger
                absorption_shield -= self.phys_dmg
                self.phys_absorbed = self.phys_dmg
                self.phys_dmg = 0
            else:
                #shield is smaller
                self.phys_dmg -= absorption_shield
                self.phys_absorbed = absorption_shield
                absorption_shield = 0
        else:
            # shield is smaller than magic_dmg, we won't get to absorb phys at all
            self.magic_dmg -= absorption_shield
            self.magic_absorbed = absorption_shield
            absorption_shield = 0

        return absorption_shield
<commit_msg>:bug: Fixed a typo in damage.py<commit_after>"""
This module will hold the damage class in the game.
"""

class Damage:
    """ This class holds the damage of every character/monster in the game"""
    def __init__(self, phys_dmg: float=0, magic_dmg: float=0):
        self.phys_dmg = round(phys_dmg, 1)
        self.magic_dmg = round(magic_dmg, 1)
        self.phys_absorbed, self.magic_absorbed = 0, 0

    def __str__(self):
        """
        Have two separate strings for physical damage and magical damage.
        Fill them if we have such damages and modify them if there is absorption
        Then, return what's appropriate
        """
        phys_dmg_print = ""
        if self.phys_dmg:
            phys_dmg_print = f'{self.phys_dmg:.2f} physical damage'

        if self.phys_absorbed:
            phys_dmg_print = f'{self.phys_dmg:.2f} physical damage ({self.phys_absorbed:.2f} absorbed)'

        magic_dmg_print = ""
        if self.magic_dmg:
            magic_dmg_print = f'{self.magic_dmg:.2f} magical damage'

        if self.magic_absorbed:
            magic_dmg_print = f'{self.magic_dmg:.2f} magical damage ({self.magic_absorbed:.2f} absorbed)'

        if phys_dmg_print and magic_dmg_print:
            return f'{phys_dmg_print} and {magic_dmg_print}'
        elif phys_dmg_print:
            return phys_dmg_print
        elif magic_dmg_print:
            return magic_dmg_print
        else:
            return "0 damage"

    def __sub__(self, other):
        return (self.phys_dmg + self.magic_dmg) - other

    def __rsub__(self, other):
        return other - (self.phys_dmg + self.magic_dmg)

    def __isub__(self, other: tuple):
        other_phys, other_magic = 0, 0  # type: int
        # unpack other damage
        if isinstance(other, tuple):
            other_phys, other_magic = other
        elif isinstance(other, Damage):
            other_phys = other.phys_dmg
            other_magic = other.magic_dmg

        # does not let the numbers get negative
        modified_phys_damage = max(self.phys_dmg - other_phys, 0)
        modified_magic_damage = max(self.magic_dmg - other_magic, 0)

        return Damage(phys_dmg=modified_phys_damage,
                      magic_dmg=modified_magic_damage)

    def __iadd__(self, other: tuple):
        other_phys, other_magic = 0, 0  # type: int
        # unpack other damage
        if isinstance(other, tuple):
            other_phys, other_magic = other
        elif isinstance(other, Damage):
            other_phys = other.phys_dmg
            other_magic = other.magic_dmg

        return Damage(phys_dmg=self.phys_dmg + other_phys,
                      magic_dmg=self.magic_dmg + other_magic)

    def __mul__(self, other: float):
        return Damage(phys_dmg=(other * self.phys_dmg),
                      magic_dmg=(other * self.magic_dmg))

    def handle_absorption(self, absorption_shield: float):
        """
        This method subtracts the absorbed damage from our damage
        The magical damage always gets absorbed first!
        :param absorption_shield: a float indicating how much damage should get absorbed
        :return: What's left of the absorption
        """

        # subtract magic damage
        if absorption_shield >= self.magic_dmg:
            # shield is bigger
            absorption_shield -= self.magic_dmg
            self.magic_absorbed = self.magic_dmg
            self.magic_dmg = 0

            # subtract physical damage
            if absorption_shield >= self.phys_dmg:
                # shield is bigger
                absorption_shield -= self.phys_dmg
                self.phys_absorbed = self.phys_dmg
                self.phys_dmg = 0
            else:
                #shield is smaller
                self.phys_dmg -= absorption_shield
                self.phys_absorbed = absorption_shield
                absorption_shield = 0
        else:
            # shield is smaller than magic_dmg, we won't get to absorb phys at all
            self.magic_dmg -= absorption_shield
            self.magic_absorbed = absorption_shield
            absorption_shield = 0

        return absorption_shield
<|endoftext|>


<commit_before>from __future__ import print_function

import gc
import math

def descending_score(results):
    return sorted(results, reverse=True, key=lambda e: e[1])

class Darwin(object):
    def __init__(self, population, serializer, evaluator, breeder):
        self.population = population
        self.serializer = serializer
        self.evaluator = evaluator
        self.breeder = breeder

        self.history = {}

    def evaluate(self, entropy):
        results = []
        for index, member in enumerate(self.population):
            print ("Evaluating", index)
            serialized = self.serializer(member)
            score = self.history.get(serialized)
            if score is None:
                score = self.evaluator(member, entropy)
                gc.collect()
                self.history[serialized] = (member, score)
            print ("Score:", score)
            results.append((member, score))
        return descending_score(results)

    def repopulate(self, survival_rate, from_history, results, entropy):
        survivor_count = int(math.ceil(len(results) * survival_rate))
        survivors = results[:survivor_count]

        best_score = survivors[0][1]
        better = []
        for entry in self.history.values():
            if (entry[1] > best_score):
                better.append(entry)
        better = descending_score(better)

        survivors.extend(better[0:from_history])

        new_population = []
        while len(new_population) < len(self.population):
            parents = [
                entropy.choice(survivors)[0],
                entropy.choice(survivors)[0]
            ]
            offspring = self.breeder(parents, entropy)
            new_population.append(offspring)
        self.population = new_population

    def best(self):
        return max(self.history.iteritems(), key=(lambda entry: entry[1][1]))[1]<commit_msg>Fix remembered scores.<commit_after>from __future__ import print_function

import gc
import math

def descending_score(results):
    return sorted(results, reverse=True, key=lambda e: e[1])

class Darwin(object):
    def __init__(self, population, serializer, evaluator, breeder):
        self.population = population
        self.serializer = serializer
        self.evaluator = evaluator
        self.breeder = breeder

        self.history = {}

    def evaluate(self, entropy):
        results = []
        for index, member in enumerate(self.population):
            print ("Evaluating", index)
            serialized = self.serializer(member)
            score = self.history.get(serialized)
            if score is None:
                score = self.evaluator(member, entropy)
                gc.collect()
                self.history[serialized] = (member, score)
            else:
                score = score[1]
            print ("Score:", score)
            results.append((member, score))
        return descending_score(results)

    def repopulate(self, survival_rate, from_history, results, entropy):
        survivor_count = int(math.ceil(len(results) * survival_rate))
        survivors = results[:survivor_count]

        best_score = survivors[0][1]
        better = []
        for entry in self.history.values():
            if (entry[1] > best_score):
                better.append(entry)
        better = descending_score(better)

        survivors.extend(better[0:from_history])

        new_population = []
        while len(new_population) < len(self.population):
            parents = [
                entropy.choice(survivors)[0],
                entropy.choice(survivors)[0]
            ]
            offspring = self.breeder(parents, entropy)
            new_population.append(offspring)
        self.population = new_population

    def best(self):
        return max(self.history.iteritems(), key=(lambda entry: entry[1][1]))[1]<|endoftext|>


<commit_before># coding=utf-8

import simplemediawiki
import sys
import unittest
try:
    import simplejson as json
except ImportError:
    import json

try:
    import http.cookiejar as cookielib
except ImportError:
    import cookielib

UNICODE_TEST = u'κόσμε'

class FetchHttpTest(unittest.TestCase):
    def setUp(self):
        self.user_agent = simplemediawiki.build_user_agent(
            'python-simplemediawiki test suite', simplemediawiki.__version__,
            'https://github.com/ianweller/python-simplemediawiki')
        self.mw = simplemediawiki.MediaWiki('https://httpbin.org/',
                                            user_agent=self.user_agent)
        self.data = None

    def _do_post(self):
        self.data = json.loads(self.mw._fetch_http('https://httpbin.org/post',
                                                   {'butts': 'lol',
                                                    'unicode': UNICODE_TEST}))

    def test_get(self):
        data = json.loads(self.mw._fetch_http('https://httpbin.org/get',
                                              {'butts': 'lol',
                                               'unicode': UNICODE_TEST},
                                              force_get=True))
        assert data['args']['format'] == 'json'
        assert data['args']['unicode'] == UNICODE_TEST

    def test_post(self):
        self._do_post()
        assert self.data is not None
        assert self.data['form']['format'] == 'json'
        assert self.data['form']['unicode'] == UNICODE_TEST

    def test_user_agent(self):
        self._do_post()
        assert self.data['headers']['User-Agent'] == self.user_agent

    def test_gzip(self):
        data = json.loads(self.mw._fetch_http('https://httpbin.org/gzip', {},
                                              force_get=True))
        assert data['gzipped'] == True

    def test_cookies(self):
        self.mw._fetch_http('https://httpbin.org/cookies/set',
                            {'unicode': UNICODE_TEST},
                            force_get=True)
        data = json.loads(self.mw._fetch_http('https://httpbin.org/cookies', {},
                                              force_get=True))
        assert 'unicode' in data['cookies']
        assert data['cookies']['unicode'] == UNICODE_TEST

    def test_persistent_cookiejar(self):
        cookiejar = cookielib.CookieJar()
        mw1 = simplemediawiki.MediaWiki('https://httpbin.org/',
                                        cookiejar=cookiejar,
                                        user_agent=self.user_agent)
        mw1._fetch_http('https://httpbin.org/cookies/set',
                        {'unicode': UNICODE_TEST}, force_get=True)
        cookiejar = mw1._cj
        mw2 = simplemediawiki.MediaWiki('https://httpbin.org/',
                                        cookiejar=cookiejar,
                                        user_agent=self.user_agent)
        data = json.loads(mw2._fetch_http('https://httpbin.org/cookies', {},
                                          force_get=True))
        print(data)
        assert 'unicode' in data['cookies']
        assert data['cookies']['unicode'] == UNICODE_TEST
<commit_msg>don't need this anymore<commit_after># coding=utf-8

import simplemediawiki
import unittest
try:
    import simplejson as json
except ImportError:
    import json

try:
    import http.cookiejar as cookielib
except ImportError:
    import cookielib

UNICODE_TEST = u'κόσμε'

class FetchHttpTest(unittest.TestCase):
    def setUp(self):
        self.user_agent = simplemediawiki.build_user_agent(
            'python-simplemediawiki test suite', simplemediawiki.__version__,
            'https://github.com/ianweller/python-simplemediawiki')
        self.mw = simplemediawiki.MediaWiki('https://httpbin.org/',
                                            user_agent=self.user_agent)
        self.data = None

    def _do_post(self):
        self.data = json.loads(self.mw._fetch_http('https://httpbin.org/post',
                                                   {'butts': 'lol',
                                                    'unicode': UNICODE_TEST}))

    def test_get(self):
        data = json.loads(self.mw._fetch_http('https://httpbin.org/get',
                                              {'butts': 'lol',
                                               'unicode': UNICODE_TEST},
                                              force_get=True))
        assert data['args']['format'] == 'json'
        assert data['args']['unicode'] == UNICODE_TEST

    def test_post(self):
        self._do_post()
        assert self.data is not None
        assert self.data['form']['format'] == 'json'
        assert self.data['form']['unicode'] == UNICODE_TEST

    def test_user_agent(self):
        self._do_post()
        assert self.data['headers']['User-Agent'] == self.user_agent

    def test_gzip(self):
        data = json.loads(self.mw._fetch_http('https://httpbin.org/gzip', {},
                                              force_get=True))
        assert data['gzipped'] == True

    def test_cookies(self):
        self.mw._fetch_http('https://httpbin.org/cookies/set',
                            {'unicode': UNICODE_TEST},
                            force_get=True)
        data = json.loads(self.mw._fetch_http('https://httpbin.org/cookies', {},
                                              force_get=True))
        assert 'unicode' in data['cookies']
        assert data['cookies']['unicode'] == UNICODE_TEST

    def test_persistent_cookiejar(self):
        cookiejar = cookielib.CookieJar()
        mw1 = simplemediawiki.MediaWiki('https://httpbin.org/',
                                        cookiejar=cookiejar,
                                        user_agent=self.user_agent)
        mw1._fetch_http('https://httpbin.org/cookies/set',
                        {'unicode': UNICODE_TEST}, force_get=True)
        cookiejar = mw1._cj
        mw2 = simplemediawiki.MediaWiki('https://httpbin.org/',
                                        cookiejar=cookiejar,
                                        user_agent=self.user_agent)
        data = json.loads(mw2._fetch_http('https://httpbin.org/cookies', {},
                                          force_get=True))
        print(data)
        assert 'unicode' in data['cookies']
        assert data['cookies']['unicode'] == UNICODE_TEST
<|endoftext|>


<commit_before>#!/usr/bin/env python2

"""Updates haproxy config based on marathon.

Features:
  - Virtual Host aliases for services
  - Soft restart of haproxy
  - SSL Termination / floating IPs
  - Live update from marathon event bus

Usage:
1. As a daemon (Must be accessible at a fixed ip/port for events from marathon)

2. Periodic runs via CRON (classic haproxy-marathon-bridge)

HA Usage:
  Run multiples instances via marathon. Unique host constraint. node name is the task id?

Configuration:
Primary source of data is marathon.
Make a list offline for the strongly  named / vhosts you want to forward
TODO: Base config for haproxy which is used as a template

Operation:
  Users must remove remove callback urls themselves. Otherwise marathon will
  forever ping nothing important
  Generates a new config file in /tmp
  Moves it to /etc/haproxy/{timestamp}

TODO:
  More reliable way to ping haproxy
  Ping apps endpoint to get environment variables to determine things like hostname to use
"""

import haproxycfggenerator
import os.path
import requests

# TODO (cmaloney): Merge with lukas' definitions
class MarathonBackend(object):
  def __init__(self, host, port):
    self.host = host
    self.port = port

  def __hash__(self):
    return hash((self.host, self.port))

class MarathonService(object):
  def __init__(self, appId, servicePort):
    self.appId = appId
    self.servicePort = servicePort
    self.backends = set()
    self.hostname = None
    self.sticky = False
    self.redirectHttpToHttps = False
    self.sslCert = None
    self.bindAddr = '*'

  def add_backend(self, host, port):
    self.backends.add(MarathonBackend(host, port))

  def __hash__(self):
    return hash(self.servicePort)

  def __eq__(self, other):
    return self.servicePort == other.servicePort

class MarathonApp(object):
  def __init__(self, marathon, appId):
    self.app = marathon.get_app(appId)
    self.appId = appId

    #port -> MarathonService
    self.services = dict()

  def __hash__(self):
    return hash(self.appId)

  def __eq__(self, other):
    return self.appId == other.appId

class Marathon(object):
  def __init__(self, hosts):
    self.__hosts = hosts

  def api_req_raw(self, method, path, body=None, **kwargs):
    for host in self.__hosts:
      path_str = os.path.join(host, 'v2')
      if len(path) == 2:
        # TODO(cmaloney): Hack to join with appIds properly
        assert(path[0] == 'apps')
        path_str += '/apps/{0}'.format(path[1])
      else:
        path_str += '/' + path[0]
      response = requests.request(
          method,
          path_str,
          headers={
              'Accept': 'application/json',
              'Content-Type': 'application/json'
              },
          **kwargs
          )
      if response.status_code == 200:
        break

    response.raise_for_status()
    return response

  def api_req(self, method, path, **kwargs):
    return self.api_req_raw(method, path, **kwargs).json()

  def create(self, app_json):
    return self.api_req('POST', ['apps'], app_json)

  def get_app(self, appid):
    return self.api_req('GET', ['apps', appid])["app"]

  # Lists all running apps.
  def list(self):
    return self.api_req('GET', ['apps'])["apps"]

  def tasks(self):
    return self.api_req('GET', ['tasks'])["tasks"]

  def add_subscriber(self, callbackUrl):
    return self.api_req('POST', ['eventSubscriptions'], params={'callbackUrl': callbackUrl})

  def remove_subscriber(self, callbackUrl):
    return self.api_req('DELETE', ['eventSubscriptions'], params={'callbackUrl': callbackUrl})

env_keys = {
  'HAPROXY_VHOST{0}': lambda x: x.hostname,
  'HAPROXY_VHOST{0}_STICKY': lambda x: x.sticky,
  'HAPROXY_VHOST{0}_REDIRECT_TO_HTTPS': lambda x: x.redirectHttpToHttps,
  'HAPROXY_VHOST{0}_SSL_CERT': lambda x: x.sslCert,
  'HAPROXY_VHOST{0}_BIND_ADDR': lambda x: x.bindAddr
}

class MarathonEventSubscriber(object):
  def __init__(self, marathon, addr):
    self.__marathon = marathon
    #NOTE: Convert to a list before handing to haproxycfggenerator
    #appId -> MarathonApp
    self.__apps = dict()
    marathon.add_subscriber(addr)

    # Fetch the base data
    self.reset_from_tasks()

  def reset_from_tasks(self):
    tasks = self.__marathon.tasks()

    self.__apps = dict()

    for task in tasks:
      # For each task, extract self.__apps
      # and the backends within each app.
      for i in xrange(len(task['servicePorts'])):
        servicePort = task['servicePorts'][i]
        port = task['ports'][i]
        appId = task['appId']

        if appId not in self.__apps:
          self.__apps[appId] = MarathonApp(self.__marathon, appId)

        app = self.__apps[appId]
        if servicePort not in app.services:
          app.services[servicePort] = MarathonService(appId, servicePort)

        service = app.services[servicePort]

        # Environment variable based config
        #TODO(cmaloney): Move to labels once those are supported throughout the stack
        for key_unformatted in env_keys:
          key = key_unformatted.format(i)
          if key in app.app[u'env']:
              env_keys[key](app.app[u'env'][key])

        service.add_backend(task['host'], port)

    # Convert to haproxycfggenerator format
    haproxy_apps = list()
    for app in self.__apps.values():
        for service in app.services.values():
            haproxy_apps.append(service)
    print haproxycfggenerator.config(haproxy_apps)

  def handle_event(self, event):
    if event['eventType'] == 'status_update_event':
      #TODO (cmaloney): Handle events more intelligently so that we add/remove things well
      self.reset_from_tasks()
<commit_msg>Environment variables<commit_after>#!/usr/bin/env python2

"""Updates haproxy config based on marathon.

Features:
  - Virtual Host aliases for services
  - Soft restart of haproxy
  - SSL Termination / floating IPs
  - Live update from marathon event bus

Usage:
1. As a daemon (Must be accessible at a fixed ip/port for events from marathon)

2. Periodic runs via CRON (classic haproxy-marathon-bridge)

HA Usage:
  Run multiples instances via marathon. Unique host constraint. node name is the task id?

Configuration:
Primary source of data is marathon.
Make a list offline for the strongly  named / vhosts you want to forward
TODO: Base config for haproxy which is used as a template

Operation:
  Users must remove remove callback urls themselves. Otherwise marathon will
  forever ping nothing important
  Generates a new config file in /tmp
  Moves it to /etc/haproxy/{timestamp}

TODO:
  More reliable way to ping haproxy
  Ping apps endpoint to get environment variables to determine things like hostname to use
"""

import haproxycfggenerator
import os.path
import requests

# TODO (cmaloney): Merge with lukas' definitions
class MarathonBackend(object):
  def __init__(self, host, port):
    self.host = host
    self.port = port

  def __hash__(self):
    return hash((self.host, self.port))

class MarathonService(object):
  def __init__(self, appId, servicePort):
    self.appId = appId
    self.servicePort = servicePort
    self.backends = set()
    self.hostname = None
    self.sticky = False
    self.redirectHttpToHttps = False
    self.sslCert = None
    self.bindAddr = '*'

  def add_backend(self, host, port):
    self.backends.add(MarathonBackend(host, port))

  def __hash__(self):
    return hash(self.servicePort)

  def __eq__(self, other):
    return self.servicePort == other.servicePort

class MarathonApp(object):
  def __init__(self, marathon, appId):
    self.app = marathon.get_app(appId)
    self.appId = appId

    #port -> MarathonService
    self.services = dict()

  def __hash__(self):
    return hash(self.appId)

  def __eq__(self, other):
    return self.appId == other.appId

class Marathon(object):
  def __init__(self, hosts):
    self.__hosts = hosts

  def api_req_raw(self, method, path, body=None, **kwargs):
    for host in self.__hosts:
      path_str = os.path.join(host, 'v2')
      if len(path) == 2:
        # TODO(cmaloney): Hack to join with appIds properly
        assert(path[0] == 'apps')
        path_str += '/apps/{0}'.format(path[1])
      else:
        path_str += '/' + path[0]
      response = requests.request(
          method,
          path_str,
          headers={
              'Accept': 'application/json',
              'Content-Type': 'application/json'
              },
          **kwargs
          )
      if response.status_code == 200:
        break

    response.raise_for_status()
    return response

  def api_req(self, method, path, **kwargs):
    return self.api_req_raw(method, path, **kwargs).json()

  def create(self, app_json):
    return self.api_req('POST', ['apps'], app_json)

  def get_app(self, appid):
    return self.api_req('GET', ['apps', appid])["app"]

  # Lists all running apps.
  def list(self):
    return self.api_req('GET', ['apps'])["apps"]

  def tasks(self):
    return self.api_req('GET', ['tasks'])["tasks"]

  def add_subscriber(self, callbackUrl):
    return self.api_req('POST', ['eventSubscriptions'], params={'callbackUrl': callbackUrl})

  def remove_subscriber(self, callbackUrl):
    return self.api_req('DELETE', ['eventSubscriptions'], params={'callbackUrl': callbackUrl})

env_keys = {
  'HAPROXY_VHOST{0}': lambda x: x.hostname,
  'HAPROXY_VHOST{0}_STICKY': lambda x: x.sticky,
  'HAPROXY_VHOST{0}_REDIRECT_TO_HTTPS': lambda x: x.redirectHttpToHttps,
  'HAPROXY_VHOST{0}_SSL_CERT': lambda x: x.sslCert,
  'HAPROXY_VHOST{0}_BIND_ADDR': lambda x: x.bindAddr
}

class MarathonEventSubscriber(object):
  def __init__(self, marathon, addr):
    self.__marathon = marathon
    #NOTE: Convert to a list before handing to haproxycfggenerator
    #appId -> MarathonApp
    self.__apps = dict()
    marathon.add_subscriber(addr)

    # Fetch the base data
    self.reset_from_tasks()

  def reset_from_tasks(self):
    tasks = self.__marathon.tasks()

    self.__apps = dict()

    for task in tasks:
      # For each task, extract self.__apps
      # and the backends within each app.
      for i in xrange(len(task['servicePorts'])):
        servicePort = task['servicePorts'][i]
        port = task['ports'][i]
        appId = task['appId']

        if appId not in self.__apps:
          self.__apps[appId] = MarathonApp(self.__marathon, appId)

        app = self.__apps[appId]
        if servicePort not in app.services:
          app.services[servicePort] = MarathonService(appId, servicePort)

        service = app.services[servicePort]

        # Environment variable based config
        #TODO(cmaloney): Move to labels once those are supported throughout the stack
        for key_unformatted in env_keys:
          key = key_unformatted.format(i)
          if key in app.app[u'env']:
              env_keys[key](service) = app.app[u'env'][key]

        service.add_backend(task['host'], port)

    # Convert to haproxycfggenerator format
    haproxy_apps = list()
    for app in self.__apps.values():
        for service in app.services.values():
            haproxy_apps.append(service)
    print haproxycfggenerator.config(haproxy_apps)

  def handle_event(self, event):
    if event['eventType'] == 'status_update_event':
      #TODO (cmaloney): Handle events more intelligently so that we add/remove things well
      self.reset_from_tasks()
<|endoftext|>


<commit_before>from frapalyzer import FRAPalyzer
import unittest

class TestFrapalyzer(unittest.TestCase):
    def setUp(self):
        self.files = [
            './test_data/data001.nd2',
            './test_data/data002.nd2'
        ]

    def test_get_background_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.background_roi)

    def test_get_stim_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.stimulation_roi)

    def test_get_ref_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.reference_roi)

    def test_get_mean_stim_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            mean = analyzer.get_mean_intensity(analyzer.stimulation_roi, False, True, True)
            self.assertAlmostEqual(mean, 112, places=0)<commit_msg>Fix test file path<commit_after>from frapalyzer import FRAPalyzer
from os import path
import unittest

class TestFrapalyzer(unittest.TestCase):
    def setUp(self):
        dir_path = path.dirname(path.realpath(__file__))
        self.files = [
            path.join(dir_path, 'test_data/data001.nd2'),
            path.join(dir_path, 'test_data/data002.nd2')
        ]

    def test_get_background_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.background_roi)

    def test_get_stim_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.stimulation_roi)

    def test_get_ref_roi_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            self.assertIsNotNone(analyzer.reference_roi)

    def test_get_mean_stim_001(self):
        with FRAPalyzer(self.files[0]) as analyzer:
            mean = analyzer.get_mean_intensity(analyzer.stimulation_roi, False, True, True)
            self.assertAlmostEqual(mean, 112, places=0)<|endoftext|>


<commit_before>"""Functional tests using the API with a fake Apple TV."""

import pyatv
import asyncio
import aiohttp
import ipaddress

from tests.log_output_handler import LogOutputHandler
from aiohttp.test_utils import (AioHTTPTestCase, unittest_run_loop)

from pyatv import (AppleTVDevice, connect_to_apple_tv, const,
                   exceptions, dmap, tag_definitions, pairing)
from tests.fake_apple_tv import (FakeAppleTV, AppleTVUseCases)
from tests import zeroconf_stub

HSGID = '12345-6789-0'
PAIRING_GUID = '0x0000000000000001'
SESSION_ID = 55555
REMOTE_NAME = 'pyatv remote'
PIN_CODE = 1234

EXPECTED_ARTWORK = b'1234'
AIRPLAY_STREAM = 'http://stream'

# This is valid for the PAIR in the pairing module and pin 1234
# (extracted form a real device)
PAIRINGCODE = '690E6FF61E0D7C747654A42AED17047D'

HOMESHARING_SERVICE_1 = zeroconf_stub.homesharing_service(
    'AAAA', b'Apple TV 1', '10.0.0.1', b'aaaa')
HOMESHARING_SERVICE_2 = zeroconf_stub.homesharing_service(
    'BBBB', b'Apple TV 2', '10.0.0.2', b'bbbb')

class FunctionalTest(AioHTTPTestCase):

    def setUp(self):
        AioHTTPTestCase.setUp(self)
        self.atv = self.get_connected_device(HSGID)
        self.log_handler = LogOutputHandler(self)

    def tearDown(self):
        self.loop.run_until_complete(self.atv.logout())
        AioHTTPTestCase.tearDown(self)
        self.log_handler.tearDown()

    @asyncio.coroutine
    def get_application(self, loop):
        self.fake_atv = FakeAppleTV(
            loop, HSGID, PAIRING_GUID, SESSION_ID, self)
        self.usecase = AppleTVUseCases(self.fake_atv)

        # Import TestServer here and not globally, otherwise py.test will
        # complain when running:
        #
        #   test_functional.py cannot collect test class 'TestServer'
        #   because it has a __init__ constructor
        from aiohttp.test_utils import TestServer
        return TestServer(self.fake_atv)

    def get_connected_device(self, identifier):
        details = AppleTVDevice(
            'Apple TV', '127.0.0.1', identifier, self.app.port)
        return connect_to_apple_tv(details, self.loop)

    @unittest_run_loop
    def test_scan_for_apple_tvs(self):
        zeroconf_stub.stub(pyatv, HOMESHARING_SERVICE_1)

        atvs = yield from pyatv.scan_for_apple_tvs(self.loop, timeout=0)
        self.assertEqual(len(atvs), 1)
        self.assertEqual(atvs[0].name, 'Apple TV 1')
        self.assertEqual(atvs[0].address, ipaddress.ip_address('10.0.0.1'))
        self.assertEqual(atvs[0].login_id, 'aaaa')
        self.assertEqual(atvs[0].port, 3689)

    @unittest_run_loop
    def test_scan_abort_on_first_found(self):
        zeroconf_stub.stub(pyatv, HOMESHARING_SERVICE_1, HOMESHARING_SERVICE_2)

        atvs = yield from pyatv.scan_for_apple_tvs(
            self.loop, timeout=0, abort_on_found=True)
        self.assertEqual(len(atvs), 1)
        self.assertEqual(atvs[0].name, 'Apple TV 1')

    # This is not a pretty test and it does crazy things. Should probably be
    # re-written later but will do for now.
    @unittest_run_loop
    def test_pairing_with_device(self):
        zeroconf = zeroconf_stub.stub(pairing)

        # Start pairing process
        handler = pyatv.pair_with_apple_tv(self.loop, PIN_CODE, REMOTE_NAME)
        yield from handler.start()

        # Verify that bonjour service was published
        self.assertEqual(len(zeroconf.registered_services), 1,
                         msg='no zeroconf service registered')

        service = zeroconf.registered_services[0]
        self.assertEqual(service.properties['DvNm'], 'pyatv remote',
                         msg='remote name does not match')

        # Extract port from service (as it is randomized) and request pairing
        # with the web server.
        server = 'http://127.0.0.1:{}'.format(service.port)
        url = '{}/pairing?pairingcode={}&servicename=test'.format(
            server, PAIRINGCODE)
        data = yield from self.simple_get(url)

        # Verify content returned in pairingresponse
        parsed = dmap.parse(data, tag_definitions.lookup_tag)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmpg'), 1)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmnm'), REMOTE_NAME)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmty'), 'ipod')

        yield from handler.stop()

    @unittest_run_loop
    def test_play_url(self):
        self.usecase.airplay_playback_idle()
        self.usecase.airplay_playback_playing()
        self.usecase.airplay_playback_idle()

        yield from self.atv.remote_control.play_url(
            AIRPLAY_STREAM, 0, port=self.app.port)

        self.assertEqual(self.fake_atv.last_airplay_url, AIRPLAY_STREAM)

    @unittest_run_loop
    def test_login_failed(self):
        # Twice since the client will retry one time
        self.usecase.make_login_fail()
        self.usecase.make_login_fail()

        with self.assertRaises(exceptions.AuthenticationError):
            yield from self.atv.login()

    # This test verifies issue #2 (automatic re-login). It uses the artwork
    # API, but it could have been any API since the login code is the same.
    @unittest_run_loop
    def test_relogin_if_session_expired(self):
        yield from self.atv.login()

        # Here, we are logged in and currently have a asession id. These
        # usescases will result in being logged out (HTTP 403) and forcing a
        # re-login with a new session id (1234)
        self.usecase.force_relogin(1234)
        self.usecase.artwork_no_permission()
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        artwork = yield from self.atv.metadata.artwork()
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_login_with_hsgid_succeed(self):
        session_id = yield from self.atv.login()
        self.assertEqual(SESSION_ID, session_id)

    @unittest_run_loop
    def test_login_with_pairing_guid_succeed(self):
        yield from self.atv.logout()
        self.atv = self.get_connected_device(PAIRING_GUID)
        session_id = yield from self.atv.login()
        self.assertEqual(SESSION_ID, session_id)

    @unittest_run_loop
    def test_button_play(self):
        yield from self.atv.remote_control.play()
        self.assertEqual(self.fake_atv.last_button_pressed, 'play')

    @unittest_run_loop
    def test_button_pause(self):
        yield from self.atv.remote_control.pause()
        self.assertEqual(self.fake_atv.last_button_pressed, 'pause')

    @unittest_run_loop
    def test_button_next(self):
        yield from self.atv.remote_control.next()
        self.assertEqual(self.fake_atv.last_button_pressed, 'nextitem')

    @unittest_run_loop
    def test_button_previous(self):
        yield from self.atv.remote_control.previous()
        self.assertEqual(self.fake_atv.last_button_pressed, 'previtem')

    @unittest_run_loop
    def test_button_select(self):
        yield from self.atv.remote_control.select()
        self.assertEqual(self.fake_atv.last_button_pressed, 'select')

    @unittest_run_loop
    def test_button_menu(self):
        yield from self.atv.remote_control.menu()
        self.assertEqual(self.fake_atv.last_button_pressed, 'menu')

    @unittest_run_loop
    def test_button_top_menu(self):
        yield from self.atv.remote_control.top_menu()
        self.assertEqual(self.fake_atv.last_button_pressed, 'topmenu')

    @unittest_run_loop
    def test_metadata_artwork(self):
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        artwork = yield from self.atv.metadata.artwork()
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_metadata_artwork_url(self):
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        # Must be logged in to have valid session id
        yield from self.atv.login()

        # URL to artwork
        artwork_url = yield from self.atv.metadata.artwork_url()

        # Fetch artwork with a GET request to ensure it works
        artwork = yield from self.simple_get(artwork_url)
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_metadata_artwork_none_if_not_available(self):
        self.usecase.change_artwork(b'')

        artwork = yield from self.atv.metadata.artwork()
        self.assertIsNone(artwork)

    @unittest_run_loop
    def test_metadata_none_type_when_not_playing(self):
        self.usecase.nothing_playing()

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_UNKNOWN)
        self.assertEqual(playing.play_state, const.PLAY_STATE_NO_MEDIA)

    @unittest_run_loop
    def test_metadata_video_paused(self):
        self.usecase.video_playing(paused=True, title='dummy',
                                   total_time=123, position=3)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_VIDEO)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PAUSED)
        self.assertEqual(playing.title, 'dummy')
        self.assertEqual(playing.total_time, 123)
        self.assertEqual(playing.position, 3)

    @unittest_run_loop
    def test_metadata_video_playing(self):
        self.usecase.video_playing(paused=False, title='video',
                                   total_time=40, position=10)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_VIDEO)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PLAYING)
        self.assertEqual(playing.title, 'video')
        self.assertEqual(playing.total_time, 40)
        self.assertEqual(playing.position, 10)

    @unittest_run_loop
    def test_metadata_music_paused(self):
        self.usecase.music_playing(paused=True, title='music',
                                   artist='artist', album='album',
                                   total_time=222, position=49)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_MUSIC)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PAUSED)
        self.assertEqual(playing.title, 'music')
        self.assertEqual(playing.artist, 'artist')
        self.assertEqual(playing.album, 'album')
        self.assertEqual(playing.total_time, 222)
        self.assertEqual(playing.position, 49)

    @unittest_run_loop
    def test_metadata_music_playing(self):
        self.usecase.music_playing(paused=False, title='music',
                                   artist='test1', album='test2',
                                   total_time=2, position=1)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_MUSIC)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PLAYING)
        self.assertEqual(playing.title, 'music')
        self.assertEqual(playing.artist, 'test1')
        self.assertEqual(playing.album, 'test2')
        self.assertEqual(playing.total_time, 2)
        self.assertEqual(playing.position, 1)

    @unittest_run_loop
    def test_push_updates(self):

        class PushListener:
            def __init__(self):
                self.playing = None

            def playstatus_update(self, updater, playstatus):
                self.playing = playstatus
                updater.stop()

            @staticmethod
            def playstatus_error(updater, exception):
                pass

        # Prepare two playstatus updates in the fake device
        self.usecase.video_playing(paused=False, title='video1',
                                   total_time=40, position=10,
                                   revision=0)
        self.usecase.video_playing(paused=True, title='video2',
                                   total_time=30, position=20,
                                   revision=1)

        # Poll the first one ("video1")
        yield from self.atv.metadata.playing()

        # Setup push updates which will instantly get the next one ("video2")
        listener = PushListener()
        self.atv.push_updater.listener = listener
        yield from self.atv.push_updater.start()

        # Check that we got the right one
        self.assertIsNotNone(listener.playing)
        self.assertEqual(listener.playing.title, 'video2')

    @unittest_run_loop
    def test_seek_in_playing_media(self):
        yield from self.atv.remote_control.set_position(60)
        self.assertEqual(self.fake_atv.properties['dacp.playingtime'], 60000)

    @unittest_run_loop
    def test_metadata_loading(self):
        self.usecase.media_is_loading()

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.play_state, const.PLAY_STATE_LOADING)

    @asyncio.coroutine
    def simple_get(self, url):
        session = aiohttp.ClientSession(loop=self.loop)
        response = yield from session.request('GET', url)
        self.assertEqual(response.status, 200,
                         msg='request to {0} failed'.format(url))
        data = yield from response.content.read()
        response.close()
        yield from session.close()
        return data
<commit_msg>Mock asyncio.sleep calls in functional tests<commit_after>"""Functional tests using the API with a fake Apple TV."""

import pyatv
import asyncio
import aiohttp
import ipaddress

from tests.log_output_handler import LogOutputHandler
from aiohttp.test_utils import (AioHTTPTestCase, unittest_run_loop)

from pyatv import (AppleTVDevice, connect_to_apple_tv, const,
                   exceptions, dmap, tag_definitions, pairing)
from tests.fake_apple_tv import (FakeAppleTV, AppleTVUseCases)
from tests import zeroconf_stub

HSGID = '12345-6789-0'
PAIRING_GUID = '0x0000000000000001'
SESSION_ID = 55555
REMOTE_NAME = 'pyatv remote'
PIN_CODE = 1234

EXPECTED_ARTWORK = b'1234'
AIRPLAY_STREAM = 'http://stream'

# This is valid for the PAIR in the pairing module and pin 1234
# (extracted form a real device)
PAIRINGCODE = '690E6FF61E0D7C747654A42AED17047D'

HOMESHARING_SERVICE_1 = zeroconf_stub.homesharing_service(
    'AAAA', b'Apple TV 1', '10.0.0.1', b'aaaa')
HOMESHARING_SERVICE_2 = zeroconf_stub.homesharing_service(
    'BBBB', b'Apple TV 2', '10.0.0.2', b'bbbb')

class FunctionalTest(AioHTTPTestCase):

    def setUp(self):
        AioHTTPTestCase.setUp(self)
        self.atv = self.get_connected_device(HSGID)
        self.log_handler = LogOutputHandler(self)

        # Make sleep calls do nothing to not slow down tests
        @asyncio.coroutine
        def fake_sleep(self, time=None, loop=None):
            pass
        from pyatv import airplay
        asyncio.sleep = fake_sleep

    def tearDown(self):
        self.loop.run_until_complete(self.atv.logout())
        AioHTTPTestCase.tearDown(self)
        self.log_handler.tearDown()

    @asyncio.coroutine
    def get_application(self, loop):
        self.fake_atv = FakeAppleTV(
            loop, HSGID, PAIRING_GUID, SESSION_ID, self)
        self.usecase = AppleTVUseCases(self.fake_atv)

        # Import TestServer here and not globally, otherwise py.test will
        # complain when running:
        #
        #   test_functional.py cannot collect test class 'TestServer'
        #   because it has a __init__ constructor
        from aiohttp.test_utils import TestServer
        return TestServer(self.fake_atv)

    def get_connected_device(self, identifier):
        details = AppleTVDevice(
            'Apple TV', '127.0.0.1', identifier, self.app.port)
        return connect_to_apple_tv(details, self.loop)

    @unittest_run_loop
    def test_scan_for_apple_tvs(self):
        zeroconf_stub.stub(pyatv, HOMESHARING_SERVICE_1)

        atvs = yield from pyatv.scan_for_apple_tvs(self.loop, timeout=0)
        self.assertEqual(len(atvs), 1)
        self.assertEqual(atvs[0].name, 'Apple TV 1')
        self.assertEqual(atvs[0].address, ipaddress.ip_address('10.0.0.1'))
        self.assertEqual(atvs[0].login_id, 'aaaa')
        self.assertEqual(atvs[0].port, 3689)

    @unittest_run_loop
    def test_scan_abort_on_first_found(self):
        zeroconf_stub.stub(pyatv, HOMESHARING_SERVICE_1, HOMESHARING_SERVICE_2)

        atvs = yield from pyatv.scan_for_apple_tvs(
            self.loop, timeout=0, abort_on_found=True)
        self.assertEqual(len(atvs), 1)
        self.assertEqual(atvs[0].name, 'Apple TV 1')

    # This is not a pretty test and it does crazy things. Should probably be
    # re-written later but will do for now.
    @unittest_run_loop
    def test_pairing_with_device(self):
        zeroconf = zeroconf_stub.stub(pairing)

        # Start pairing process
        handler = pyatv.pair_with_apple_tv(self.loop, PIN_CODE, REMOTE_NAME)
        yield from handler.start()

        # Verify that bonjour service was published
        self.assertEqual(len(zeroconf.registered_services), 1,
                         msg='no zeroconf service registered')

        service = zeroconf.registered_services[0]
        self.assertEqual(service.properties['DvNm'], 'pyatv remote',
                         msg='remote name does not match')

        # Extract port from service (as it is randomized) and request pairing
        # with the web server.
        server = 'http://127.0.0.1:{}'.format(service.port)
        url = '{}/pairing?pairingcode={}&servicename=test'.format(
            server, PAIRINGCODE)
        data = yield from self.simple_get(url)

        # Verify content returned in pairingresponse
        parsed = dmap.parse(data, tag_definitions.lookup_tag)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmpg'), 1)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmnm'), REMOTE_NAME)
        self.assertEqual(dmap.first(parsed, 'cmpa', 'cmty'), 'ipod')

        yield from handler.stop()

    @unittest_run_loop
    def test_play_url(self):
        self.usecase.airplay_playback_idle()
        self.usecase.airplay_playback_playing()
        self.usecase.airplay_playback_idle()

        yield from self.atv.remote_control.play_url(
            AIRPLAY_STREAM, 0, port=self.app.port)

        self.assertEqual(self.fake_atv.last_airplay_url, AIRPLAY_STREAM)

    @unittest_run_loop
    def test_login_failed(self):
        # Twice since the client will retry one time
        self.usecase.make_login_fail()
        self.usecase.make_login_fail()

        with self.assertRaises(exceptions.AuthenticationError):
            yield from self.atv.login()

    # This test verifies issue #2 (automatic re-login). It uses the artwork
    # API, but it could have been any API since the login code is the same.
    @unittest_run_loop
    def test_relogin_if_session_expired(self):
        yield from self.atv.login()

        # Here, we are logged in and currently have a asession id. These
        # usescases will result in being logged out (HTTP 403) and forcing a
        # re-login with a new session id (1234)
        self.usecase.force_relogin(1234)
        self.usecase.artwork_no_permission()
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        artwork = yield from self.atv.metadata.artwork()
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_login_with_hsgid_succeed(self):
        session_id = yield from self.atv.login()
        self.assertEqual(SESSION_ID, session_id)

    @unittest_run_loop
    def test_login_with_pairing_guid_succeed(self):
        yield from self.atv.logout()
        self.atv = self.get_connected_device(PAIRING_GUID)
        session_id = yield from self.atv.login()
        self.assertEqual(SESSION_ID, session_id)

    @unittest_run_loop
    def test_button_play(self):
        yield from self.atv.remote_control.play()
        self.assertEqual(self.fake_atv.last_button_pressed, 'play')

    @unittest_run_loop
    def test_button_pause(self):
        yield from self.atv.remote_control.pause()
        self.assertEqual(self.fake_atv.last_button_pressed, 'pause')

    @unittest_run_loop
    def test_button_next(self):
        yield from self.atv.remote_control.next()
        self.assertEqual(self.fake_atv.last_button_pressed, 'nextitem')

    @unittest_run_loop
    def test_button_previous(self):
        yield from self.atv.remote_control.previous()
        self.assertEqual(self.fake_atv.last_button_pressed, 'previtem')

    @unittest_run_loop
    def test_button_select(self):
        yield from self.atv.remote_control.select()
        self.assertEqual(self.fake_atv.last_button_pressed, 'select')

    @unittest_run_loop
    def test_button_menu(self):
        yield from self.atv.remote_control.menu()
        self.assertEqual(self.fake_atv.last_button_pressed, 'menu')

    @unittest_run_loop
    def test_button_top_menu(self):
        yield from self.atv.remote_control.top_menu()
        self.assertEqual(self.fake_atv.last_button_pressed, 'topmenu')

    @unittest_run_loop
    def test_metadata_artwork(self):
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        artwork = yield from self.atv.metadata.artwork()
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_metadata_artwork_url(self):
        self.usecase.change_artwork(EXPECTED_ARTWORK)

        # Must be logged in to have valid session id
        yield from self.atv.login()

        # URL to artwork
        artwork_url = yield from self.atv.metadata.artwork_url()

        # Fetch artwork with a GET request to ensure it works
        artwork = yield from self.simple_get(artwork_url)
        self.assertEqual(artwork, EXPECTED_ARTWORK)

    @unittest_run_loop
    def test_metadata_artwork_none_if_not_available(self):
        self.usecase.change_artwork(b'')

        artwork = yield from self.atv.metadata.artwork()
        self.assertIsNone(artwork)

    @unittest_run_loop
    def test_metadata_none_type_when_not_playing(self):
        self.usecase.nothing_playing()

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_UNKNOWN)
        self.assertEqual(playing.play_state, const.PLAY_STATE_NO_MEDIA)

    @unittest_run_loop
    def test_metadata_video_paused(self):
        self.usecase.video_playing(paused=True, title='dummy',
                                   total_time=123, position=3)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_VIDEO)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PAUSED)
        self.assertEqual(playing.title, 'dummy')
        self.assertEqual(playing.total_time, 123)
        self.assertEqual(playing.position, 3)

    @unittest_run_loop
    def test_metadata_video_playing(self):
        self.usecase.video_playing(paused=False, title='video',
                                   total_time=40, position=10)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_VIDEO)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PLAYING)
        self.assertEqual(playing.title, 'video')
        self.assertEqual(playing.total_time, 40)
        self.assertEqual(playing.position, 10)

    @unittest_run_loop
    def test_metadata_music_paused(self):
        self.usecase.music_playing(paused=True, title='music',
                                   artist='artist', album='album',
                                   total_time=222, position=49)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_MUSIC)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PAUSED)
        self.assertEqual(playing.title, 'music')
        self.assertEqual(playing.artist, 'artist')
        self.assertEqual(playing.album, 'album')
        self.assertEqual(playing.total_time, 222)
        self.assertEqual(playing.position, 49)

    @unittest_run_loop
    def test_metadata_music_playing(self):
        self.usecase.music_playing(paused=False, title='music',
                                   artist='test1', album='test2',
                                   total_time=2, position=1)

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.media_type, const.MEDIA_TYPE_MUSIC)
        self.assertEqual(playing.play_state, const.PLAY_STATE_PLAYING)
        self.assertEqual(playing.title, 'music')
        self.assertEqual(playing.artist, 'test1')
        self.assertEqual(playing.album, 'test2')
        self.assertEqual(playing.total_time, 2)
        self.assertEqual(playing.position, 1)

    @unittest_run_loop
    def test_push_updates(self):

        class PushListener:
            def __init__(self):
                self.playing = None

            def playstatus_update(self, updater, playstatus):
                self.playing = playstatus
                updater.stop()

            @staticmethod
            def playstatus_error(updater, exception):
                pass

        # Prepare two playstatus updates in the fake device
        self.usecase.video_playing(paused=False, title='video1',
                                   total_time=40, position=10,
                                   revision=0)
        self.usecase.video_playing(paused=True, title='video2',
                                   total_time=30, position=20,
                                   revision=1)

        # Poll the first one ("video1")
        yield from self.atv.metadata.playing()

        # Setup push updates which will instantly get the next one ("video2")
        listener = PushListener()
        self.atv.push_updater.listener = listener
        yield from self.atv.push_updater.start()

        # Check that we got the right one
        self.assertIsNotNone(listener.playing)
        self.assertEqual(listener.playing.title, 'video2')

    @unittest_run_loop
    def test_seek_in_playing_media(self):
        yield from self.atv.remote_control.set_position(60)
        self.assertEqual(self.fake_atv.properties['dacp.playingtime'], 60000)

    @unittest_run_loop
    def test_metadata_loading(self):
        self.usecase.media_is_loading()

        playing = yield from self.atv.metadata.playing()
        self.assertEqual(playing.play_state, const.PLAY_STATE_LOADING)

    @asyncio.coroutine
    def simple_get(self, url):
        session = aiohttp.ClientSession(loop=self.loop)
        response = yield from session.request('GET', url)
        self.assertEqual(response.status, 200,
                         msg='request to {0} failed'.format(url))
        data = yield from response.content.read()
        response.close()
        yield from session.close()
        return data
<|endoftext|>


<commit_before>__version__ = '0.1'<commit_msg>Bump version<commit_after>__version__ = '0.1.1'<|endoftext|>


<commit_before># flake8: noqa
import platform
import unittest
from os import environ

def check_env(key: str, default=None):
    return environ.get(key, default)

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class CoreImportTest(unittest.TestCase):

    def test_import_event_engine(self):
        from vnpy.event import EventEngine

    def test_import_main_engine(self):
        from vnpy.trader.engine import MainEngine

    def test_import_ui(self):
        from vnpy.trader.ui import MainWindow, create_qapp

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class GatewayImportTest(unittest.TestCase):

    def test_import_binance(self):
        from vnpy.gateway.binance import BinanceGateway

    def test_import_bitfinex(self):
        from vnpy.gateway.bitfinex import BitfinexGateway

    def test_import_bitmex(self):
        from vnpy.gateway.bitmex import BitmexGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    def test_import_ctp(self):
        from vnpy.gateway.ctp import CtpGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_ctptest(self):
        from vnpy.gateway.ctptest import CtptestGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_femas(self):
        from vnpy.gateway.femas import FemasGateway

    def test_import_futu(self):
        from vnpy.gateway.futu import FutuGateway

    def test_import_hbdm(self):
        from vnpy.gateway.hbdm import HbdmGateway

    def test_import_huobi(self):
        from vnpy.gateway.huobi import HuobiGateway

    def test_import_ib(self):
        from vnpy.gateway.ib import IbGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(check_env('VNPY_BUILD_OES') == '0', "Skip because of VNPY_BUILD_OES==0")
    def test_import_oes(self):
        from vnpy.gateway.oes import OesGateway

    def test_import_okex(self):
        from vnpy.gateway.okex import OkexGateway

    def test_import_okexf(self):
        from vnpy.gateway.okexf import OkexfGateway

    def test_import_onetoken(self):
        from vnpy.gateway.onetoken import OnetokenGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_tap(self):
        from vnpy.gateway.tap import TapGateway

    def test_import_tiger(self):
        from vnpy.gateway.tiger import TigerGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_tora(self):
        from vnpy.gateway.tora import ToraGateway

    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    def test_import_xtp(self):
        from vnpy.gateway.xtp import XtpGateway

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AppImportTest(unittest.TestCase):

    def test_import_cta_strategy_app(self):
        from vnpy.app.cta_strategy import CtaStrategyApp

    def test_import_csv_loader_app(self):
        from vnpy.app.csv_loader import CsvLoaderApp

if __name__ == '__main__':
    unittest.main()
<commit_msg>[Add] skip some tests if module not built<commit_after># flake8: noqa
import platform
import unittest
from os import environ

def check_env(key: str, default=None):
    return environ.get(key, default)

def skip_if_module_not_built(env_key: str):
    return unittest.skipIf(
        check_env(key=env_key) == '0',
        f"Skip because of {env_key}==0",
    )

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class CoreImportTest(unittest.TestCase):

    def test_import_event_engine(self):
        from vnpy.event import EventEngine

    def test_import_main_engine(self):
        from vnpy.trader.engine import MainEngine

    def test_import_ui(self):
        from vnpy.trader.ui import MainWindow, create_qapp

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class GatewayImportTest(unittest.TestCase):

    def test_import_binance(self):
        from vnpy.gateway.binance import BinanceGateway

    def test_import_bitfinex(self):
        from vnpy.gateway.bitfinex import BitfinexGateway

    def test_import_bitmex(self):
        from vnpy.gateway.bitmex import BitmexGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @skip_if_module_not_built(env_key="VNPY_BUILD_CTP")
    def test_import_ctp(self):
        from vnpy.gateway.ctp import CtpGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_ctptest(self):
        from vnpy.gateway.ctptest import CtptestGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_femas(self):
        from vnpy.gateway.femas import FemasGateway

    def test_import_futu(self):
        from vnpy.gateway.futu import FutuGateway

    def test_import_hbdm(self):
        from vnpy.gateway.hbdm import HbdmGateway

    def test_import_huobi(self):
        from vnpy.gateway.huobi import HuobiGateway

    def test_import_ib(self):
        from vnpy.gateway.ib import IbGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @skip_if_module_not_built(env_key="VNPY_BUILD_OES")
    def test_import_oes(self):
        from vnpy.gateway.oes import OesGateway

    def test_import_okex(self):
        from vnpy.gateway.okex import OkexGateway

    def test_import_okexf(self):
        from vnpy.gateway.okexf import OkexfGateway

    def test_import_onetoken(self):
        from vnpy.gateway.onetoken import OnetokenGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_tap(self):
        from vnpy.gateway.tap import TapGateway

    def test_import_tiger(self):
        from vnpy.gateway.tiger import TigerGateway

    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    def test_import_tora(self):
        from vnpy.gateway.tora import ToraGateway

    @unittest.skipIf(platform.system() == "Linux", "Not supported yet under Linux")
    @unittest.skipIf(platform.system() == "Darwin", "Not supported yet under osx")
    def test_import_xtp(self):
        from vnpy.gateway.xtp import XtpGateway

# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AppImportTest(unittest.TestCase):

    def test_import_cta_strategy_app(self):
        from vnpy.app.cta_strategy import CtaStrategyApp

    def test_import_csv_loader_app(self):
        from vnpy.app.csv_loader import CsvLoaderApp

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


<commit_before>import numpy as np
from numpy.testing import assert_array_equal

from pystruct.problems import LatentGridCRF, LatentDirectionalGridCRF
from pystruct.learners import (LatentSSVM, StructuredSVM, OneSlackSSVM,
                               SubgradientSSVM)

import pystruct.toy_datasets as toy

def test_with_crosses():
    # very simple dataset. k-means init is perfect
    for n_states_per_label in [2, [1, 2]]:
        # test with 2 states for both foreground and background,
        # as well as with single background state
        #for inference_method in ['ad3', 'qpbo', 'lp']:
        for inference_method in ['lp']:
            X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                        total_size=8)
            n_labels = 2
            crf = LatentGridCRF(n_labels=n_labels,
                                n_states_per_label=n_states_per_label,
                                inference_method=inference_method)
            clf = LatentSSVM(StructuredSVM(problem=crf, max_iter=50, C=10. **
                                           5, verbose=2,
                                           check_constraints=True, n_jobs=-1,
                                           break_on_bad=True))
            clf.fit(X, Y)
            Y_pred = clf.predict(X)
            assert_array_equal(np.array(Y_pred), Y)

def test_with_crosses_base_svms():
    # very simple dataset. k-means init is perfect
    n_labels = 2
    crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=[1, 2],
                        inference_method='lp')
    one_slack = OneSlackSSVM(crf)
    n_slack = StructuredSVM(crf)
    subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)

    for base_ssvm in [one_slack, n_slack, subgradient]:
        base_ssvm.C = 10. ** 5
        base_ssvm.n_jobs = -1
        X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                    total_size=8)
        clf = LatentSSVM(base_ssvm=base_ssvm)
        clf.fit(X, Y)
        Y_pred = clf.predict(X)
        assert_array_equal(np.array(Y_pred), Y)

def test_with_crosses_bad_init():
    # use less perfect initialization
    X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                total_size=8)
    n_labels = 2
    crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2,
                        inference_method='lp')
    H_init = crf.init_latent(X, Y)

    mask = np.random.uniform(size=H_init.shape) > .7
    H_init[mask] = 2 * (H_init[mask] / 2)

    one_slack = OneSlackSSVM(crf)
    n_slack = StructuredSVM(crf)
    subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)

    for base_ssvm in [one_slack, n_slack, subgradient]:
        base_ssvm.C = 10. ** 3
        base_ssvm.n_jobs = -1
        clf = LatentSSVM(base_ssvm)

        clf.fit(X, Y, H_init=H_init)
        Y_pred = clf.predict(X)

        assert_array_equal(np.array(Y_pred), Y)

def test_directional_bars():
    for inference_method in ['lp']:
        X, Y = toy.generate_easy(n_samples=10, noise=5, box_size=2,
                                 total_size=6, seed=1)
        n_labels = 2
        crf = LatentDirectionalGridCRF(n_labels=n_labels,
                                       n_states_per_label=[1, 4],
                                       inference_method=inference_method)
        clf = LatentSSVM(OneSlackSSVM(problem=crf, max_iter=500, C=10. ** 5,
                                      verbose=2, check_constraints=True,
                                      n_jobs=-1, break_on_bad=True))
        clf.fit(X, Y)
        Y_pred = clf.predict(X)

        assert_array_equal(np.array(Y_pred), Y)
<commit_msg>faster test for latent svm using parameters to one slack<commit_after>import numpy as np
from numpy.testing import assert_array_equal

from pystruct.problems import LatentGridCRF, LatentDirectionalGridCRF
from pystruct.learners import (LatentSSVM, StructuredSVM, OneSlackSSVM,
                               SubgradientSSVM)

import pystruct.toy_datasets as toy

def test_with_crosses():
    # very simple dataset. k-means init is perfect
    for n_states_per_label in [2, [1, 2]]:
        # test with 2 states for both foreground and background,
        # as well as with single background state
        #for inference_method in ['ad3', 'qpbo', 'lp']:
        for inference_method in ['lp']:
            X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                        total_size=8)
            n_labels = 2
            crf = LatentGridCRF(n_labels=n_labels,
                                n_states_per_label=n_states_per_label,
                                inference_method=inference_method)
            clf = LatentSSVM(StructuredSVM(problem=crf, max_iter=50, C=10. **
                                           5, verbose=2,
                                           check_constraints=True, n_jobs=-1,
                                           break_on_bad=True))
            clf.fit(X, Y)
            Y_pred = clf.predict(X)
            assert_array_equal(np.array(Y_pred), Y)

def test_with_crosses_base_svms():
    # very simple dataset. k-means init is perfect
    n_labels = 2
    crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=[1, 2],
                        inference_method='lp')
    one_slack = OneSlackSSVM(crf)
    n_slack = StructuredSVM(crf)
    subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)

    for base_ssvm in [one_slack, n_slack, subgradient]:
        base_ssvm.C = 10. ** 5
        base_ssvm.n_jobs = -1
        X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                    total_size=8)
        clf = LatentSSVM(base_ssvm=base_ssvm)
        clf.fit(X, Y)
        Y_pred = clf.predict(X)
        assert_array_equal(np.array(Y_pred), Y)

def test_with_crosses_bad_init():
    # use less perfect initialization
    X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
                                total_size=8)
    n_labels = 2
    crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2,
                        inference_method='lp')
    H_init = crf.init_latent(X, Y)

    mask = np.random.uniform(size=H_init.shape) > .7
    H_init[mask] = 2 * (H_init[mask] / 2)

    one_slack = OneSlackSSVM(crf, inactive_threshold=1e-8, cache_tol=.0001,
                             inference_cache=50, max_iter=10000)
    n_slack = StructuredSVM(crf)
    subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)

    for base_ssvm in [one_slack, n_slack, subgradient]:
        base_ssvm.C = 10. ** 3
        base_ssvm.n_jobs = -1
        clf = LatentSSVM(base_ssvm)

        clf.fit(X, Y, H_init=H_init)
        Y_pred = clf.predict(X)

        assert_array_equal(np.array(Y_pred), Y)

def test_directional_bars():
    for inference_method in ['lp']:
        X, Y = toy.generate_easy(n_samples=10, noise=5, box_size=2,
                                 total_size=6, seed=1)
        n_labels = 2
        crf = LatentDirectionalGridCRF(n_labels=n_labels,
                                       n_states_per_label=[1, 4],
                                       inference_method=inference_method)
        clf = LatentSSVM(OneSlackSSVM(problem=crf, max_iter=500, C=10. ** 5,
                                      verbose=2, check_constraints=True,
                                      n_jobs=-1, break_on_bad=True))
        clf.fit(X, Y)
        Y_pred = clf.predict(X)

        assert_array_equal(np.array(Y_pred), Y)
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import librato
import os
import unittest

from librato_bg import Client
from mock import patch

class MockConnection(object):
    def __init__(self, items):
        self.items = items

    class Queue(object):
        def __init__(self, items):
            self.items = items

        def add(self, name, value, source):
            self.items.append({'name': name, 'value': value, 'source': source})

        def submit(self):
            pass

    def new_queue(self):
        print("new_queue")
        return MockConnection.Queue(self.items)

class TestClient(unittest.TestCase):
    def setUp(self):
        super(TestClient, self).setUp()

        self.mock_queue = []
        with patch.object(librato, 'connect') as mock_connect:
            mock_connect.return_value = MockConnection(self.mock_queue)
            self.client = Client('test-user', '1234567890', debug=True)

    def test_gauge(self):
        self.client.gauge('librato_bg.test', 105, 'lagom')
        self.client.flush()

        self.assertEqual(self.mock_queue, [{'name': 'librato_bg.test', 'source': 'lagom', 'value': 105}])

if __name__ == '__main__':
    """
    We can also test against a real Librato account
    """
    user = os.environ.get('LIBRATO_USER')
    token = os.environ.get('LIBRATO_TOKEN')

    assert user and token, "Must set LIBRATO_USER and LIBRATO_TOKEN to run tests"
    client = Client(user, token, debug=True)

    for i in range(1000):
        client.gauge('librato_bg.test', i, 'lagom')
    client.flush()
<commit_msg>Remove cruft<commit_after>from __future__ import unicode_literals

import librato
import os
import unittest

from librato_bg import Client
from mock import patch

class MockConnection(object):
    def __init__(self, items):
        self.items = items

    class Queue(object):
        def __init__(self, items):
            self.items = items

        def add(self, name, value, source):
            self.items.append({'name': name, 'value': value, 'source': source})

        def submit(self):
            pass

    def new_queue(self):
        return MockConnection.Queue(self.items)

class TestClient(unittest.TestCase):
    def setUp(self):
        super(TestClient, self).setUp()

        self.mock_queue = []
        with patch.object(librato, 'connect') as mock_connect:
            mock_connect.return_value = MockConnection(self.mock_queue)
            self.client = Client('test-user', '1234567890', debug=True)

    def test_gauge(self):
        self.client.gauge('librato_bg.test', 105, 'lagom')
        self.client.flush()

        self.assertEqual(self.mock_queue, [{'name': 'librato_bg.test', 'source': 'lagom', 'value': 105}])

if __name__ == '__main__':
    """
    We can also test against a real Librato account
    """
    user = os.environ.get('LIBRATO_USER')
    token = os.environ.get('LIBRATO_TOKEN')

    assert user and token, "Must set LIBRATO_USER and LIBRATO_TOKEN to run tests"
    client = Client(user, token, debug=True)

    for i in range(1000):
        client.gauge('librato_bg.test', i, 'lagom')
    client.flush()
<|endoftext|>