<commit_before>import os.path as op

import numpy as nm

from sfepy import data_dir

from sfepy.base.testing import TestCommon

def init_vec(variables):
    return nm.random.rand(variables.di.ptr[-1])

class Test(TestCommon):

    @staticmethod
    def from_conf(conf, options):
        from sfepy.discrete import FieldVariable, Variables, Problem
        from sfepy.discrete.fem import Mesh, FEDomain, Field

        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
        domain = FEDomain('domain', mesh)

        omega = domain.create_region('Omega', 'all')
        domain.create_region('Left',
                             'vertices in (x < -0.499)',
                             'facet')
        domain.create_region('LeftStrip',
                             'vertices in (x < -0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('LeftFix',
                             'r.Left -v r.LeftStrip',
                             'facet')
        domain.create_region('Right',
                             'vertices in (x > 0.499)',
                             'facet')
        domain.create_region('RightStrip',
                             'vertices in (x > 0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('RightFix',
                             'r.Right -v r.RightStrip',
                             'facet')

        fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
        u = FieldVariable('u', 'unknown', fu)

        fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
        p = FieldVariable('p', 'unknown', fp)

        pb = Problem('test', domain=domain, fields=[fu, fp],
                     auto_conf=False, auto_solvers=False)

        test = Test(problem=pb, variables=Variables([u, p]),
                    conf=conf, options=options)
        return test

    def test_ebcs(self):
        from sfepy.discrete.conditions import Conditions, EssentialBC
        from sfepy.discrete.common.dof_info import expand_nodes_to_equations

        variables = self.variables
        regions = self.problem.domain.regions

        all_ebcs = []
        all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'],
                                    {'u.all' : nm.array([0.0, 1.0])}))
        all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'],
                                    {'u.0' : 0.0, 'u.1' : 1.0}))
        all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'],
                                    {'p.all' : 0.0}))
        all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'],
                                    {'p.0' : 0.0}))
        all_ebcs.append([EssentialBC('fix_p3', regions['Right'],
                                     {'p.0' : 0.0}),
                         EssentialBC('fix_u3', regions['Left'],
                                     {'u.0' : 0.0, 'u.1' : 1.0})])

        ok = True
        for ii, bcs in enumerate(all_ebcs):
            if not isinstance(bcs, list): bcs = [bcs]

            ebcs = Conditions(bcs)
            variables.equation_mapping(ebcs=ebcs, epbcs=None,
                                       ts=None, functions=None)
            vec = init_vec(variables)
            variables.apply_ebc(vec)

            for var_name, var_bcs in ebcs.group_by_variables().iteritems():
                var = variables[var_name]
                for bc in var_bcs:
                    bc.canonize_dof_names(var.dofs)
                    self.report('%d: %s %s: %s %s'
                                % (ii, var.name,
                                   bc.name, bc.region.name, bc.dofs[0]))
                    nods = var.field.get_dofs_in_region(bc.region)
                    eq = expand_nodes_to_equations(nods, bc.dofs[0], var.dofs)

                    off = variables.di.indx[var_name].start
                    n_nod = len(nods)
                    for bdof, dof_name in enumerate(bc.dofs[0]):
                        idof = var.dofs.index(dof_name)
                        eqs = eq[n_nod * bdof : n_nod * (bdof + 1)]

                        _ok = nm.allclose(vec[off + eqs], idof,
                                          atol=1e-14, rtol=0.0)
                        if not _ok:
                            self.report(' %s: failed! (all of %s == %f)'
                                        % (dof_name, vec[off + eqs], idof))
                        ok = ok and _ok

        return ok

    def test_epbcs(self):
        from sfepy.discrete import Function, Functions
        from sfepy.discrete.conditions import Conditions, PeriodicBC
        from sfepy.discrete.common.dof_info import expand_nodes_to_equations
        from sfepy.discrete.fem.periodic import match_y_line

        variables = self.variables
        regions = self.problem.domain.regions

        match_y_line = Function('match_y_line', match_y_line)
        pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']],
                         {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line')

        functions = Functions([match_y_line])

        epbcs = Conditions([pbc])
        variables.equation_mapping(ebcs=None, epbcs=epbcs,
                                   ts=None, functions=functions)

        vec = init_vec(variables)
        variables.apply_ebc(vec)

        var = variables['u']
        var_bcs = epbcs.group_by_variables()['u']
        bc = var_bcs['pbc']
        bc.canonize_dof_names(var.dofs)

        nods0 = var.field.get_dofs_in_region(bc.regions[0])
        nods1 = var.field.get_dofs_in_region(bc.regions[1])

        coors0 = var.field.get_coor(nods0)
        coors1 = var.field.get_coor(nods1)
        i0, i1 = match_y_line(coors0, coors1)

        eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs)
        eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs)

        ok = True

        _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0
        if not _ok:
            self.report('master equations mismatch! (set(%s) == set(%s))'
                        % (eq0, var.eq_map.master))
        ok = ok and _ok

        _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0
        if not _ok:
            self.report('slave equations mismatch! (set(%s) == set(%s))'
                        % (eq1, var.eq_map.slave))
        ok = ok and _ok

        off = variables.di.indx['u'].start
        _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0)
        if not _ok:
            self.report('periodicity test failed! (%s == %s)'
                        % (vec[off + eq0], vec[off + eq0]))
        ok = ok and _ok

        return ok

    def test_save_ebc(self):
        from sfepy.discrete import (FieldVariable, Integral,
                                    Equation, Equations, Problem)
        from sfepy.discrete.conditions import Conditions, EssentialBC
        from sfepy.terms import Term

        name = op.join(self.options.out_dir,
                       op.splitext(op.basename(__file__))[0])

        integral = Integral('i', order=1)

        u = self.variables['u']
        v = FieldVariable('v', 'test', u.field, primary_var_name='u')

        p = self.variables['p']
        q = FieldVariable('q', 'test', p.field, primary_var_name='p')

        regions = self.problem.domain.regions
        omega = regions['Omega']

        # Problem.save_ebc() requires to have equations defined.
        t1 = Term.new('dw_lin_elastic(v, u)',
                      integral, omega, v=v, u=u)
        t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p)
        eq = Equation('aux', t1 + t2)
        eqs = Equations([eq])

        pb = Problem('test', equations=eqs, auto_solvers=False)

        all_ebcs = []
        all_ebcs.append(EssentialBC('fix_u1', regions['RightFix'],
                                    {'u.all' : nm.array([0.0, 1.0])}))
        all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'],
                                    {'u.0' : 0.0, 'u.1' : 1.0}))
        all_ebcs.append(EssentialBC('fix_p1', regions['LeftFix'],
                                    {'p.all' : 0.0}))
        all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'],
                                    {'p.0' : 0.0}))
        ebcs = Conditions(all_ebcs)

        pb.time_update(ebcs=ebcs)

        pb.save_ebc(name + '_ebcs_f.vtk', ebcs=ebcs, force=True)
        pb.save_ebc(name + '_ebcs.vtk', ebcs=ebcs, default=-1, force=False)

        return True
<commit_msg>move checking of applied conditions from test_ebcs() into new check_vec()<commit_after>import os.path as op

import numpy as nm

from sfepy import data_dir

from sfepy.base.testing import TestCommon

def init_vec(variables):
    return nm.random.rand(variables.di.ptr[-1])

def check_vec(self, vec, ii, ok, conds, variables):
    from sfepy.discrete.common.dof_info import expand_nodes_to_equations

    for var_name, var_conds in conds.group_by_variables().iteritems():
        var = variables[var_name]
        for cond in var_conds:
            cond.canonize_dof_names(var.dofs)
            self.report('%d: %s %s: %s %s'
                        % (ii, var.name,
                           cond.name, cond.region.name, cond.dofs[0]))
            nods = var.field.get_dofs_in_region(cond.region)
            eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)

            off = variables.di.indx[var_name].start
            n_nod = len(nods)
            for cdof, dof_name in enumerate(cond.dofs[0]):
                idof = var.dofs.index(dof_name)
                eqs = eq[n_nod * cdof : n_nod * (cdof + 1)]

                _ok = nm.allclose(vec[off + eqs], idof,
                                  atol=1e-14, rtol=0.0)
                if not _ok:
                    self.report(' %s: failed! (all of %s == %f)'
                                % (dof_name, vec[off + eqs], idof))
                ok = ok and _ok

    return ok

class Test(TestCommon):

    @staticmethod
    def from_conf(conf, options):
        from sfepy.discrete import FieldVariable, Variables, Problem
        from sfepy.discrete.fem import Mesh, FEDomain, Field

        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
        domain = FEDomain('domain', mesh)

        omega = domain.create_region('Omega', 'all')
        domain.create_region('Left',
                             'vertices in (x < -0.499)',
                             'facet')
        domain.create_region('LeftStrip',
                             'vertices in (x < -0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('LeftFix',
                             'r.Left -v r.LeftStrip',
                             'facet')
        domain.create_region('Right',
                             'vertices in (x > 0.499)',
                             'facet')
        domain.create_region('RightStrip',
                             'vertices in (x > 0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('RightFix',
                             'r.Right -v r.RightStrip',
                             'facet')

        fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
        u = FieldVariable('u', 'unknown', fu)

        fp = Field.from_args('fp', nm.float64, 'scalar', omega, approx_order=2)
        p = FieldVariable('p', 'unknown', fp)

        pb = Problem('test', domain=domain, fields=[fu, fp],
                     auto_conf=False, auto_solvers=False)

        test = Test(problem=pb, variables=Variables([u, p]),
                    conf=conf, options=options)
        return test

    def test_ebcs(self):
        from sfepy.discrete.conditions import Conditions, EssentialBC

        variables = self.variables
        regions = self.problem.domain.regions

        all_ebcs = []
        all_ebcs.append(EssentialBC('fix_u1', regions['LeftFix'],
                                    {'u.all' : nm.array([0.0, 1.0])}))
        all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'],
                                    {'u.0' : 0.0, 'u.1' : 1.0}))
        all_ebcs.append(EssentialBC('fix_p1', regions['RightFix'],
                                    {'p.all' : 0.0}))
        all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'],
                                    {'p.0' : 0.0}))
        all_ebcs.append([EssentialBC('fix_p3', regions['Right'],
                                     {'p.0' : 0.0}),
                         EssentialBC('fix_u3', regions['Left'],
                                     {'u.0' : 0.0, 'u.1' : 1.0})])

        ok = True
        for ii, bcs in enumerate(all_ebcs):
            if not isinstance(bcs, list): bcs = [bcs]

            ebcs = Conditions(bcs)
            variables.equation_mapping(ebcs=ebcs, epbcs=None,
                                       ts=None, functions=None)
            vec = init_vec(variables)
            variables.apply_ebc(vec)

            ok = check_vec(self, vec, ii, ok, ebcs, variables)

        return ok

    def test_epbcs(self):
        from sfepy.discrete import Function, Functions
        from sfepy.discrete.conditions import Conditions, PeriodicBC
        from sfepy.discrete.common.dof_info import expand_nodes_to_equations
        from sfepy.discrete.fem.periodic import match_y_line

        variables = self.variables
        regions = self.problem.domain.regions

        match_y_line = Function('match_y_line', match_y_line)
        pbc = PeriodicBC('pbc', [regions['LeftStrip'], regions['RightStrip']],
                         {'u.[1,0]' : 'u.[0,1]'}, match='match_y_line')

        functions = Functions([match_y_line])

        epbcs = Conditions([pbc])
        variables.equation_mapping(ebcs=None, epbcs=epbcs,
                                   ts=None, functions=functions)

        vec = init_vec(variables)
        variables.apply_ebc(vec)

        var = variables['u']
        var_bcs = epbcs.group_by_variables()['u']
        bc = var_bcs['pbc']
        bc.canonize_dof_names(var.dofs)

        nods0 = var.field.get_dofs_in_region(bc.regions[0])
        nods1 = var.field.get_dofs_in_region(bc.regions[1])

        coors0 = var.field.get_coor(nods0)
        coors1 = var.field.get_coor(nods1)
        i0, i1 = match_y_line(coors0, coors1)

        eq0 = expand_nodes_to_equations(nods0[i0], bc.dofs[0], var.dofs)
        eq1 = expand_nodes_to_equations(nods1[i1], bc.dofs[1], var.dofs)

        ok = True

        _ok = len(nm.setdiff1d(eq0, var.eq_map.master)) == 0
        if not _ok:
            self.report('master equations mismatch! (set(%s) == set(%s))'
                        % (eq0, var.eq_map.master))
        ok = ok and _ok

        _ok = len(nm.setdiff1d(eq1, var.eq_map.slave)) == 0
        if not _ok:
            self.report('slave equations mismatch! (set(%s) == set(%s))'
                        % (eq1, var.eq_map.slave))
        ok = ok and _ok

        off = variables.di.indx['u'].start
        _ok = nm.allclose(vec[off + eq0], vec[off + eq1], atol=1e-14, rtol=0.0)
        if not _ok:
            self.report('periodicity test failed! (%s == %s)'
                        % (vec[off + eq0], vec[off + eq0]))
        ok = ok and _ok

        return ok

    def test_save_ebc(self):
        from sfepy.discrete import (FieldVariable, Integral,
                                    Equation, Equations, Problem)
        from sfepy.discrete.conditions import Conditions, EssentialBC
        from sfepy.terms import Term

        name = op.join(self.options.out_dir,
                       op.splitext(op.basename(__file__))[0])

        integral = Integral('i', order=1)

        u = self.variables['u']
        v = FieldVariable('v', 'test', u.field, primary_var_name='u')

        p = self.variables['p']
        q = FieldVariable('q', 'test', p.field, primary_var_name='p')

        regions = self.problem.domain.regions
        omega = regions['Omega']

        # Problem.save_ebc() requires to have equations defined.
        t1 = Term.new('dw_lin_elastic(v, u)',
                      integral, omega, v=v, u=u)
        t2 = Term.new('dw_laplace(q, p)', integral, omega, q=q, p=p)
        eq = Equation('aux', t1 + t2)
        eqs = Equations([eq])

        pb = Problem('test', equations=eqs, auto_solvers=False)

        all_ebcs = []
        all_ebcs.append(EssentialBC('fix_u1', regions['RightFix'],
                                    {'u.all' : nm.array([0.0, 1.0])}))
        all_ebcs.append(EssentialBC('fix_u2', regions['LeftStrip'],
                                    {'u.0' : 0.0, 'u.1' : 1.0}))
        all_ebcs.append(EssentialBC('fix_p1', regions['LeftFix'],
                                    {'p.all' : 0.0}))
        all_ebcs.append(EssentialBC('fix_p2', regions['RightStrip'],
                                    {'p.0' : 0.0}))
        ebcs = Conditions(all_ebcs)

        pb.time_update(ebcs=ebcs)

        pb.save_ebc(name + '_ebcs_f.vtk', ebcs=ebcs, force=True)
        pb.save_ebc(name + '_ebcs.vtk', ebcs=ebcs, default=-1, force=False)

        return True
<|endoftext|>


<commit_before># -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2017 SciFabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PYBOSSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PYBOSSA.  If not, see <http://www.gnu.org/licenses/>.
import json
from pbsonesignal import PybossaOneSignal
from pbsonesignal.exceptions import *
from nose.tools import raises
from mock import patch, MagicMock

class TestPybossaOnesignal(object):

    error_app = {'errors': ['error']}

    valid_app = {u'safari_icon_16_16': u'16x16.png',
                 u'chrome_web_gcm_sender_id': u'',
                 u'site_name': None,
                 u'safari_site_origin': None,
                 u'safari_icon_32_32': u'16x16@2x.png',
                 u'safari_apns_certificate': None,
                 u'updated_at': u'2017-04-20T14:03:05.985Z',
                 u'basic_auth_key': u'key',
                 u'messageable_players': 0,
                 u'id': u'id',
                 u'safari_icon_256_256': u'128x128@2x.png',
                 u'chrome_web_origin': u'https://scifabric.com',
                 u'safari_push_id': None,
                 u'safari_icon_64_64': u'32x32@2x.png',
                 u'apns_certificates': None,
                 u'chrome_web_default_notification_icon': u'https://scifabric.com/img',
                 u'name': u'name', u'gcm_key': None,
                 u'created_at': u'2017-04-20T14:03:05.883Z',
                 u'chrome_web_sub_domain': u'',
                 u'players': 0, u'apns_env': None,
                 u'chrome_key': None,
                 u'chrome_web_key': u'(OneSignal Shared Google Server API Key)',
                 u'safari_icon_128_128': u'128x128.png'}

    payload = None

    def setUp(self):
        self.payload = {
                        "included_segments": ["All"],
                        "excluded_sements": [],
                        "filters": [],
                        "contents": {"en": "English Message"},
                        "headings": {"en": "Heading"},
                        "url": "https://yoursite.com/",
                        "web_buttons": [{"id": "read-more-button",
                                        "text": "Read more",
                                        "icon": "http://i.imgur.com/MIxJp1L.png",
                                        "url": "https://yoursite.com"}],
                        "chrome_web_image": "https://yourimage.com",
                        "chrome_web_icon": "https://image"}

    @patch('pbsonesignal.requests.post')
    def test_create_app(self, mock):
        """Test create_app works."""
        client = PybossaOneSignal(app_id="1", api_key="algo", auth_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_app
        mock.return_value = fakeRequest
        tmp = client.create_app('name', 'https://scifabric.com', 'https://scifabric.com/img')
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_app

    @raises(CreateApp)
    @patch('pbsonesignal.requests.post')
    def test_create_app_errors(self, mock):
        """Test create_app errors works."""
        client = PybossaOneSignal(app_id="1", api_key="algo", auth_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 400
        fakeRequest.reason = 'Bad Status'
        fakeRequest.json.return_value = self.error_app
        mock.return_value = fakeRequest
        tmp = client.create_app('name', 'https://scifabric.com', 'https://scifabric.com/img')
        assert tmp[0] == 400
        assert tmp[1] == 'Bad Status'
        assert tmp[2] == self.error_app
<commit_msg>Fixes.<commit_after># -*- coding: utf8 -*-
# This file is part of PYBOSSA.
#
# Copyright (C) 2017 SciFabric LTD.
#
# PYBOSSA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PYBOSSA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PYBOSSA.  If not, see <http://www.gnu.org/licenses/>.
import json
from pbsonesignal import PybossaOneSignal
from pbsonesignal.exceptions import *
from nose.tools import raises
from mock import patch, MagicMock

class TestPybossaOnesignal(object):

    error_app = {'errors': ['error']}

    valid_app = {u'safari_icon_16_16': u'16x16.png',
                 u'chrome_web_gcm_sender_id': u'',
                 u'site_name': None,
                 u'safari_site_origin': None,
                 u'safari_icon_32_32': u'16x16@2x.png',
                 u'safari_apns_certificate': None,
                 u'updated_at': u'2017-04-20T14:03:05.985Z',
                 u'basic_auth_key': u'key',
                 u'messageable_players': 0,
                 u'id': u'id',
                 u'safari_icon_256_256': u'128x128@2x.png',
                 u'chrome_web_origin': u'https://scifabric.com',
                 u'safari_push_id': None,
                 u'safari_icon_64_64': u'32x32@2x.png',
                 u'apns_certificates': None,
                 u'chrome_web_default_notification_icon': u'https://scifabric.com/img',
                 u'name': u'name', u'gcm_key': None,
                 u'created_at': u'2017-04-20T14:03:05.883Z',
                 u'chrome_web_sub_domain': u'',
                 u'players': 0, u'apns_env': None,
                 u'chrome_key': None,
                 u'chrome_web_key': u'(OneSignal Shared Google Server API Key)',
                 u'safari_icon_128_128': u'128x128.png'}

    payload = None

    def setUp(self):
        self.payload = {
                        "included_segments": ["All"],
                        "excluded_sements": [],
                        "filters": [],
                        "contents": {"en": "English Message"},
                        "headings": {"en": "Heading"},
                        "url": "https://yoursite.com/",
                        "web_buttons": [{"id": "read-more-button",
                                        "text": "Read more",
                                        "icon": "http://i.imgur.com/MIxJp1L.png",
                                        "url": "https://yoursite.com"}],
                        "chrome_web_image": "https://yourimage.com",
                        "chrome_web_icon": "https://image"}

    @raises(AuthKeyMissing)
    def test_create_app_no_auth_key(self):
        """Test create_app without auth_key."""
        client = PybossaOneSignal(api_key="key")
        client.create_app('name', 'https://scifabric.com', 'https://scifabric.com/img')

    @patch('pbsonesignal.requests.post')
    def test_create_app(self, mock):
        """Test create_app works."""
        client = PybossaOneSignal(app_id="1", api_key="algo", auth_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 200
        fakeRequest.reason = 'OK'
        fakeRequest.json.return_value = self.valid_app
        mock.return_value = fakeRequest
        tmp = client.create_app('name', 'https://scifabric.com', 'https://scifabric.com/img')
        assert tmp[0] == 200
        assert tmp[1] == 'OK'
        assert tmp[2] == self.valid_app

    @raises(CreateApp)
    @patch('pbsonesignal.requests.post')
    def test_create_app_errors(self, mock):
        """Test create_app errors works."""
        client = PybossaOneSignal(app_id="1", api_key="algo", auth_key="key")
        fakeRequest = MagicMock()
        fakeRequest.status_code = 400
        fakeRequest.reason = 'Bad Status'
        fakeRequest.json.return_value = self.error_app
        mock.return_value = fakeRequest
        tmp = client.create_app('name', 'https://scifabric.com', 'https://scifabric.com/img')
        assert tmp[0] == 400
        assert tmp[1] == 'Bad Status'
        assert tmp[2] == self.error_app
<|endoftext|>


<commit_before>from __future__ import division, print_function
import numpy as np
from mp_base import *

def mp_cross_gtis(gti_list, bin_time=1, debug=True):
    ninst = len(gti_list)
    if ninst == 1:
        return gti_list[0]

    start = np.min([g[0][0] for g in gti_list])
    stop = np.max([g[-1][-1] for g in gti_list])

    times = np.arange(start, stop, 1, dtype=np.longdouble)

    mask0 = mp_create_gti_mask(times, gti_list[0], verbose=0)

    if debug:
        step = 1
        colors = ['k', 'r', 'g', 'b']
        colors += colors + colors + colors
        import matplotlib.pyplot as plt
        for g in gti_list[0]:
            plt.plot([g[0], g[1]], [0, 0], color=colors[0], lw=5)
            plt.axvline(g[0], color=colors[0])
            plt.axvline(g[1], color=colors[0], ls='--')
    for ig, gti in enumerate(gti_list):
        mask = mp_create_gti_mask(times, gti, verbose=0)
        mask0 = np.logical_and(mask0, mask)
        if debug:
            for g in gti:
                plt.plot([g[0], g[1]], [ig * step, ig * step],
                         color=colors[ig], lw=5)
                plt.axvline(g[0], color=colors[ig])
                plt.axvline(g[1], color=colors[ig], ls='--')

    gtis = mp_create_gti_from_condition(times, mask0)
    if debug:
        ig += 1
        for g in gti:
            plt.plot([g[0], g[1]], [ig * step, ig * step],
                     color=colors[ig], lw=5)
            plt.axvline(g[0], color=colors[ig])
            plt.axvline(g[1], color=colors[ig], ls='--')

        plt.ylim([-10, 10])
        plt.show()
    return gtis
<commit_msg>Minor change<commit_after>from __future__ import division, print_function
import numpy as np
from mp_base import mp_create_gti_mask, mp_create_gti_from_condition

def mp_cross_gtis(gti_list, bin_time=1, debug=True):
    ninst = len(gti_list)
    if ninst == 1:
        return gti_list[0]

    start = np.min([g[0][0] for g in gti_list])
    stop = np.max([g[-1][-1] for g in gti_list])

    times = np.arange(start, stop, 1, dtype=np.longdouble)

    mask0 = mp_create_gti_mask(times, gti_list[0], verbose=0)

    if debug:
        step = 1
        colors = ['k', 'r', 'g', 'b']
        colors += colors + colors + colors
        import matplotlib.pyplot as plt
        for g in gti_list[0]:
            plt.plot([g[0], g[1]], [0, 0], color=colors[0], lw=5)
            plt.axvline(g[0], color=colors[0])
            plt.axvline(g[1], color=colors[0], ls='--')
    for ig, gti in enumerate(gti_list):
        mask = mp_create_gti_mask(times, gti, verbose=0)
        mask0 = np.logical_and(mask0, mask)
        if debug:
            for g in gti:
                plt.plot([g[0], g[1]], [ig * step, ig * step],
                         color=colors[ig], lw=5)
                plt.axvline(g[0], color=colors[ig])
                plt.axvline(g[1], color=colors[ig], ls='--')

    gtis = mp_create_gti_from_condition(times, mask0)
    if debug:
        ig += 1
        for g in gti:
            plt.plot([g[0], g[1]], [ig * step, ig * step],
                     color=colors[ig], lw=5)
            plt.axvline(g[0], color=colors[ig])
            plt.axvline(g[1], color=colors[ig], ls='--')

        plt.ylim([-10, 10])
        plt.show()
    return gtis
<|endoftext|>


<commit_before>from click.testing import CliRunner
import matplotlib.pyplot as plt
import soundfile
import wandb
import numpy as np
import pytest
import PIL
import os
import matplotlib
import six

matplotlib.use("Agg")

data = np.random.randint(255, size=(1000))

def test_raw_data():
    wbhist = wandb.Histogram(data)
    assert len(wbhist.histogram) == 64

def test_np_histogram():
    wbhist = wandb.Histogram(np_histogram=np.histogram(data))
    assert len(wbhist.histogram) == 10

def test_manual_histogram():
    wbhist = wandb.Histogram(np_histogram=([1, 2, 4], [3, 10, 20, 0]))
    assert len(wbhist.histogram) == 3

def test_fucked_up_histogram():
    with pytest.raises(ValueError):
        wbhist = wandb.Histogram(np_histogram=([1, 2, 3], [1]))

def test_transform():
    wbhist = wandb.Histogram(data)
    json = wandb.Histogram.transform(wbhist)
    assert json["_type"] == "histogram"
    assert len(json["values"]) == 64

image = np.random.randint(255, size=(28, 28))

def test_captions():
    wbone = wandb.Image(image, caption="Cool")
    wbtwo = wandb.Image(image, caption="Nice")
    assert wandb.Image.captions([wbone, wbtwo]) == ["Cool", "Nice"]

def test_transform():
    with CliRunner().isolated_filesystem():
        meta = wandb.Image.transform([wandb.Image(image)], ".", "test.jpg")
        assert meta == {'_type': 'images',
                        'count': 1, 'height': 28, 'width': 28}
        assert os.path.exists("media/images/test.jpg")

def test_audio_sample_rates():
    audio1 = np.random.uniform(-1, 1, 44100)
    audio2 = np.random.uniform(-1, 1, 88200)
    wbaudio1 = wandb.Audio(audio1, sample_rate=44100)
    wbaudio2 = wandb.Audio(audio2, sample_rate=88200)
    assert wandb.Audio.sample_rates([wbaudio1, wbaudio2]) == [44100, 88200]
    # test with missing sample rate
    with pytest.raises(ValueError):
        wbaudio3 = wandb.Audio(audio1)

def test_audio_durations():
    audio1 = np.random.uniform(-1, 1, 44100)
    audio2 = np.random.uniform(-1, 1, 88200)
    wbaudio1 = wandb.Audio(audio1, sample_rate=44100)
    wbaudio2 = wandb.Audio(audio2, sample_rate=44100)
    assert wandb.Audio.durations([wbaudio1, wbaudio2]) == [1.0, 2.0]

def test_audio_captions():
    audio = np.random.uniform(-1, 1, 44100)
    sample_rate = 44100
    caption1 = "This is what a dog sounds like"
    caption2 = "This is what a chicken sounds like"
    # test with all captions
    wbaudio1 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption1)
    wbaudio2 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption2)
    assert wandb.Audio.captions([wbaudio1, wbaudio2]) == [caption1, caption2]
    # test with no captions
    wbaudio3 = wandb.Audio(audio, sample_rate=sample_rate)
    wbaudio4 = wandb.Audio(audio, sample_rate=sample_rate)
    assert wandb.Audio.captions([wbaudio3, wbaudio4]) == False
    # test with some captions
    wbaudio5 = wandb.Audio(audio, sample_rate=sample_rate)
    wbaudio6 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption2)
    assert wandb.Audio.captions([wbaudio5, wbaudio6]) == ['', caption2]

def test_audio_transform():
    audio = np.random.uniform(-1, 1, 44100)
    with CliRunner().isolated_filesystem():
        meta = wandb.Audio.transform(
            [wandb.Audio(audio, sample_rate=44100)], ".", "test", 0)
        assert meta == {'_type': 'audio',
                        'count': 1, 'sampleRates': [44100], 'durations': [1.0]}
        assert os.path.exists("media/audio/test_0_0.wav")

def test_guess_mode():
    image = np.random.randint(255, size=(28, 28, 3))
    wbimg = wandb.Image(image)
    assert wbimg.image.mode == "RGB"

def test_pil():
    pil = PIL.Image.new("L", (28, 28))
    img = wandb.Image(pil)
    assert img.image == pil

def test_matplotlib_image():
    plt.plot([1, 2, 2, 4])
    img = wandb.Image(plt)
    assert img.image.width == 640

def test_html_str():
    with CliRunner().isolated_filesystem():
        html = wandb.Html("
Hello
")
        wandb.Html.transform([html], ".", "rad", "summary")
        assert os.path.exists("media/html/rad_summary_0.html")

def test_html_styles():
    with CliRunner().isolated_filesystem():
        pre = '<base target="_blank"><link rel="stylesheet" type="text/css" href="https://app.wandb.ai/normalize.css" />'
        html = wandb.Html("
Hello
")
        assert html.html == ""+pre + \
            "
Hello
"
        html = wandb.Html(
            "
Hello
")
        assert html.html == ""+pre + \
            "
Hello
"
        html = wandb.Html("
Hello
")
        assert html.html == pre + "
Hello
"
        html = wandb.Html("
Hello
", inject=False)
        assert html.html == "
Hello
"

def test_html_file():
    with CliRunner().isolated_filesystem():
        with open("test.html", "w") as f:
            f.write("
Hello
")
        html = wandb.Html(open("test.html"))
        wandb.Html.transform([html, html], ".", "rad", "summary")
        assert os.path.exists("media/html/rad_summary_0.html")
        assert os.path.exists("media/html/rad_summary_1.html")

def test_table_default():
    table = wandb.Table()
    table.add_data("Some awesome text", "Positive", "Negative")
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["Some awesome text", "Positive", "Negative"]],
                                            "columns": ["Input", "Output", "Expected"]}

def test_table_custom():
    table = wandb.Table(["Foo", "Bar"])
    table.add_data("So", "Cool")
    table.add_row("&", "Rad")
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["So", "Cool"], ["&", "Rad"]],
                                            "columns": ["Foo", "Bar"]}

point_cloud = np.array([[0, 0, 0, 1],
                        [0, 0, 1, 2],
                        [0, 1, 0, 2],
                        [0, 1, 0, 4]])

def test_object3d_numpy():
    obj = wandb.Object3D(point_cloud)
    np.testing.assert_array_equal(obj.numpyData, point_cloud)

def test_object3d_obj():
    obj = wandb.Object3D(open("tests/fixtures/cube.obj"))
    assert obj.extension == "obj"

def test_object3d_gltf():
    obj = wandb.Object3D(open("tests/fixtures/Box.gltf"))
    assert obj.extension == "gltf"

def test_object3d_io():
    f = open("tests/fixtures/Box.gltf")
    body = f.read()
    ioObj = six.StringIO(unicode(body, "utf-8"))
    obj = wandb.Object3D(ioObj, file_type="obj")

    assert obj.extension == "obj"

def test_object3d_unsupported_numpy():
    with pytest.raises(ValueError):
        wandb.Object3D(np.array([1]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([[1, 2], [3, 4], [1, 2]]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([1, 3, 4, 5, 6, 7, 8, 8, 3]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([[1, 3, 4, 5, 6, 7, 8, 8, 3]]))

    f = open("tests/fixtures/Box.gltf")
    body = f.read()
    ioObj = six.StringIO(unicode(body, "utf-8"))

    with pytest.raises(ValueError):
        obj = wandb.Object3D(ioObj)

def test_object3d_transform():
    obj = wandb.Object3D.transform([
        wandb.Object3D(open("tests/fixtures/Box.gltf")),
        wandb.Object3D(open("tests/fixtures/cube.obj")),
        wandb.Object3D(point_cloud)], "tests/output", "pc", 1)

    assert os.path.exists("tests/output/media/object3D/pc_1_0.gltf")
    assert os.path.exists("tests/output/media/object3D/pc_1_1.obj")
    assert os.path.exists(
        "tests/output/media/object3D/pc_1_2.pts.json")

    assert obj["_type"] == "object3D"
    assert obj["filenames"] == [
        "pc_1_0.gltf",
        "pc_1_1.obj",
        "pc_1_2.pts.json",
    ]

def test_table_init():
    table = wandb.Table(data=[["Some awesome text", "Positive", "Negative"]])
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["Some awesome text", "Positive", "Negative"]],
                                            "columns": ["Input", "Output", "Expected"]}
<commit_msg>More compatibility<commit_after>from click.testing import CliRunner
import matplotlib.pyplot as plt
import soundfile
import wandb
import numpy as np
import pytest
import PIL
import os
import matplotlib
import six

matplotlib.use("Agg")

data = np.random.randint(255, size=(1000))

def test_raw_data():
    wbhist = wandb.Histogram(data)
    assert len(wbhist.histogram) == 64

def test_np_histogram():
    wbhist = wandb.Histogram(np_histogram=np.histogram(data))
    assert len(wbhist.histogram) == 10

def test_manual_histogram():
    wbhist = wandb.Histogram(np_histogram=([1, 2, 4], [3, 10, 20, 0]))
    assert len(wbhist.histogram) == 3

def test_fucked_up_histogram():
    with pytest.raises(ValueError):
        wbhist = wandb.Histogram(np_histogram=([1, 2, 3], [1]))

def test_transform():
    wbhist = wandb.Histogram(data)
    json = wandb.Histogram.transform(wbhist)
    assert json["_type"] == "histogram"
    assert len(json["values"]) == 64

image = np.random.randint(255, size=(28, 28))

def test_captions():
    wbone = wandb.Image(image, caption="Cool")
    wbtwo = wandb.Image(image, caption="Nice")
    assert wandb.Image.captions([wbone, wbtwo]) == ["Cool", "Nice"]

def test_transform():
    with CliRunner().isolated_filesystem():
        meta = wandb.Image.transform([wandb.Image(image)], ".", "test.jpg")
        assert meta == {'_type': 'images',
                        'count': 1, 'height': 28, 'width': 28}
        assert os.path.exists("media/images/test.jpg")

def test_audio_sample_rates():
    audio1 = np.random.uniform(-1, 1, 44100)
    audio2 = np.random.uniform(-1, 1, 88200)
    wbaudio1 = wandb.Audio(audio1, sample_rate=44100)
    wbaudio2 = wandb.Audio(audio2, sample_rate=88200)
    assert wandb.Audio.sample_rates([wbaudio1, wbaudio2]) == [44100, 88200]
    # test with missing sample rate
    with pytest.raises(ValueError):
        wbaudio3 = wandb.Audio(audio1)

def test_audio_durations():
    audio1 = np.random.uniform(-1, 1, 44100)
    audio2 = np.random.uniform(-1, 1, 88200)
    wbaudio1 = wandb.Audio(audio1, sample_rate=44100)
    wbaudio2 = wandb.Audio(audio2, sample_rate=44100)
    assert wandb.Audio.durations([wbaudio1, wbaudio2]) == [1.0, 2.0]

def test_audio_captions():
    audio = np.random.uniform(-1, 1, 44100)
    sample_rate = 44100
    caption1 = "This is what a dog sounds like"
    caption2 = "This is what a chicken sounds like"
    # test with all captions
    wbaudio1 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption1)
    wbaudio2 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption2)
    assert wandb.Audio.captions([wbaudio1, wbaudio2]) == [caption1, caption2]
    # test with no captions
    wbaudio3 = wandb.Audio(audio, sample_rate=sample_rate)
    wbaudio4 = wandb.Audio(audio, sample_rate=sample_rate)
    assert wandb.Audio.captions([wbaudio3, wbaudio4]) == False
    # test with some captions
    wbaudio5 = wandb.Audio(audio, sample_rate=sample_rate)
    wbaudio6 = wandb.Audio(audio, sample_rate=sample_rate, caption=caption2)
    assert wandb.Audio.captions([wbaudio5, wbaudio6]) == ['', caption2]

def test_audio_transform():
    audio = np.random.uniform(-1, 1, 44100)
    with CliRunner().isolated_filesystem():
        meta = wandb.Audio.transform(
            [wandb.Audio(audio, sample_rate=44100)], ".", "test", 0)
        assert meta == {'_type': 'audio',
                        'count': 1, 'sampleRates': [44100], 'durations': [1.0]}
        assert os.path.exists("media/audio/test_0_0.wav")

def test_guess_mode():
    image = np.random.randint(255, size=(28, 28, 3))
    wbimg = wandb.Image(image)
    assert wbimg.image.mode == "RGB"

def test_pil():
    pil = PIL.Image.new("L", (28, 28))
    img = wandb.Image(pil)
    assert img.image == pil

def test_matplotlib_image():
    plt.plot([1, 2, 2, 4])
    img = wandb.Image(plt)
    assert img.image.width == 640

def test_html_str():
    with CliRunner().isolated_filesystem():
        html = wandb.Html("
Hello
")
        wandb.Html.transform([html], ".", "rad", "summary")
        assert os.path.exists("media/html/rad_summary_0.html")

def test_html_styles():
    with CliRunner().isolated_filesystem():
        pre = '<base target="_blank"><link rel="stylesheet" type="text/css" href="https://app.wandb.ai/normalize.css" />'
        html = wandb.Html("
Hello
")
        assert html.html == ""+pre + \
            "
Hello
"
        html = wandb.Html(
            "
Hello
")
        assert html.html == ""+pre + \
            "
Hello
"
        html = wandb.Html("
Hello
")
        assert html.html == pre + "
Hello
"
        html = wandb.Html("
Hello
", inject=False)
        assert html.html == "
Hello
"

def test_html_file():
    with CliRunner().isolated_filesystem():
        with open("test.html", "w") as f:
            f.write("
Hello
")
        html = wandb.Html(open("test.html"))
        wandb.Html.transform([html, html], ".", "rad", "summary")
        assert os.path.exists("media/html/rad_summary_0.html")
        assert os.path.exists("media/html/rad_summary_1.html")

def test_table_default():
    table = wandb.Table()
    table.add_data("Some awesome text", "Positive", "Negative")
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["Some awesome text", "Positive", "Negative"]],
                                            "columns": ["Input", "Output", "Expected"]}

def test_table_custom():
    table = wandb.Table(["Foo", "Bar"])
    table.add_data("So", "Cool")
    table.add_row("&", "Rad")
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["So", "Cool"], ["&", "Rad"]],
                                            "columns": ["Foo", "Bar"]}

point_cloud = np.array([[0, 0, 0, 1],
                        [0, 0, 1, 2],
                        [0, 1, 0, 2],
                        [0, 1, 0, 4]])

def test_object3d_numpy():
    obj = wandb.Object3D(point_cloud)
    np.testing.assert_array_equal(obj.numpyData, point_cloud)

def test_object3d_obj():
    obj = wandb.Object3D(open("tests/fixtures/cube.obj"))
    assert obj.extension == "obj"

def test_object3d_gltf():
    obj = wandb.Object3D(open("tests/fixtures/Box.gltf"))
    assert obj.extension == "gltf"

def test_object3d_io():
    f = open("tests/fixtures/Box.gltf")
    body = f.read()
    ioObj = six.StringIO(six.text_type(body, "utf-8"))
    obj = wandb.Object3D(ioObj, file_type="obj")

    assert obj.extension == "obj"

def test_object3d_unsupported_numpy():
    with pytest.raises(ValueError):
        wandb.Object3D(np.array([1]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([[1, 2], [3, 4], [1, 2]]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([1, 3, 4, 5, 6, 7, 8, 8, 3]))

    with pytest.raises(ValueError):
        wandb.Object3D(np.array([[1, 3, 4, 5, 6, 7, 8, 8, 3]]))

    f = open("tests/fixtures/Box.gltf")
    body = f.read()
    ioObj = six.StringIO(six.text_type(body, "utf-8"))

    with pytest.raises(ValueError):
        obj = wandb.Object3D(ioObj)

def test_object3d_transform():
    obj = wandb.Object3D.transform([
        wandb.Object3D(open("tests/fixtures/Box.gltf")),
        wandb.Object3D(open("tests/fixtures/cube.obj")),
        wandb.Object3D(point_cloud)], "tests/output", "pc", 1)

    assert os.path.exists("tests/output/media/object3D/pc_1_0.gltf")
    assert os.path.exists("tests/output/media/object3D/pc_1_1.obj")
    assert os.path.exists(
        "tests/output/media/object3D/pc_1_2.pts.json")

    assert obj["_type"] == "object3D"
    assert obj["filenames"] == [
        "pc_1_0.gltf",
        "pc_1_1.obj",
        "pc_1_2.pts.json",
    ]

def test_table_init():
    table = wandb.Table(data=[["Some awesome text", "Positive", "Negative"]])
    assert wandb.Table.transform(table) == {"_type": "table",
                                            "data": [["Some awesome text", "Positive", "Negative"]],
                                            "columns": ["Input", "Output", "Expected"]}
<|endoftext|>


<commit_before># coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rasa_core.channels import CollectingOutputChannel
from rasa_core.dispatcher import Button, Element, Dispatcher
from rasa_core.domain import TemplateDomain
from rasa_core.nlg import TemplatedNaturalLanguageGenerator
from rasa_core.trackers import DialogueStateTracker

def test_dispatcher_utter_attachment(default_dispatcher_collecting):
    default_dispatcher_collecting.utter_attachment("http://my-attachment")
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert {'recipient_id': 'my-sender',
            'text': 'Image: http://my-attachment'} == collected

def test_dispatcher_utter_template(default_dispatcher_collecting,
                                   default_tracker):
    default_dispatcher_collecting.utter_template("utter_goodbye",
                                                 default_tracker)
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert collected['text'] in {"goodbye 😢", "bye bye 😢"}

def test_dispatcher_handle_unknown_template(default_dispatcher_collecting,
                                            default_tracker):
    default_dispatcher_collecting.utter_template("my_made_up_template",
                                                 default_tracker)
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert collected['text'].startswith("Undefined utter template")

def test_dispatcher_template_invalid_vars():
    templates = {
                "my_made_up_template": [{
                    "text": "a template referencing an invalid {variable}."}]}
    bot = CollectingOutputChannel()
    nlg = TemplatedNaturalLanguageGenerator(templates)
    dispatcher = Dispatcher("my-sender", bot, nlg)
    tracker = DialogueStateTracker("my-sender", slots=[])
    dispatcher.utter_template("my_made_up_template", tracker)
    collected = dispatcher.output_channel.latest_output()
    assert collected['text'].startswith(
            "a template referencing an invalid {variable}.")

def test_dispatcher_utter_response(default_dispatcher_collecting):
    text_only_message = {"text": "hey"}
    image_only_message = {"image": "https://i.imgur.com/nGF1K8f.jpg"}
    text_and_image_message = {
        "text": "look at this",
        "image": "https://i.imgur.com/T5xVo.jpg"
    }

    default_dispatcher_collecting.utter_response(text_only_message)
    default_dispatcher_collecting.utter_response(image_only_message)
    default_dispatcher_collecting.utter_response(text_and_image_message)
    collected = default_dispatcher_collecting.output_channel.messages

    assert len(collected) == 4
    assert collected[0] == {"recipient_id": "my-sender", "text": "hey"}
    assert collected[1] == {
        "recipient_id": "my-sender",
        "text": "Image: https://i.imgur.com/nGF1K8f.jpg"}
    assert collected[2] == {"recipient_id": "my-sender", "text": "look at this"}
    assert collected[3] == {
        "recipient_id": "my-sender",
        "text": "Image: https://i.imgur.com/T5xVo.jpg"}

def test_dispatcher_utter_buttons(default_dispatcher_collecting):
    buttons = [
        Button(title="Btn1", payload="/btn1"),
        Button(title="Btn2", payload="/btn2")
    ]
    default_dispatcher_collecting.utter_button_message("my message", buttons)
    collected = default_dispatcher_collecting.output_channel.messages
    assert len(collected) == 1
    assert collected[0]['text'] == "my message"
    assert collected[0]['data'] == [
        {'payload': u'/btn1', 'title': u'Btn1'},
        {'payload': u'/btn2', 'title': u'Btn2'}
    ]

def test_dispatcher_utter_buttons_from_domain_templ(default_tracker):
    domain_file = "examples/moodbot/domain.yml"
    domain = TemplateDomain.load(domain_file)
    bot = CollectingOutputChannel()
    nlg = TemplatedNaturalLanguageGenerator(domain.templates)
    dispatcher = Dispatcher("my-sender", bot, nlg)
    dispatcher.utter_template("utter_greet", default_tracker)
    assert len(bot.messages) == 1
    assert bot.messages[0]['text'] == "Hey! How are you?"
    assert bot.messages[0]['data'] == [
        {'payload': 'great', 'title': 'great'},
        {'payload': 'super sad', 'title': 'super sad'}
    ]

def test_dispatcher_utter_custom_message(default_dispatcher_collecting):
    elements = [
        Element(title="hey there", subtitle="welcome", buttons=[
            Button(title="Btn1", payload="/btn1"),
            Button(title="Btn2", payload="/btn2")]),
        Element(title="another title", subtitle="another subtitle", buttons=[
            Button(title="Btn3", payload="/btn3"),
            Button(title="Btn4", payload="/btn4")])
    ]
    default_dispatcher_collecting.utter_custom_message(*elements)
    collected = default_dispatcher_collecting.output_channel.messages
    assert len(collected) == 2
    assert collected[0]['text'] == "hey there : welcome"
    assert collected[0]['data'] == [
        {'payload': u'/btn1', 'title': u'Btn1'},
        {'payload': u'/btn2', 'title': u'Btn2'}
    ]
    assert collected[1]['text'] == "another title : another subtitle"
    assert collected[1]['data'] == [
        {'payload': u'/btn3', 'title': u'Btn3'},
        {'payload': u'/btn4', 'title': u'Btn4'}
    ]
<commit_msg>Update test_dispatcher.py<commit_after># coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rasa_core.channels import CollectingOutputChannel
from rasa_core.dispatcher import Button, Element, Dispatcher
from rasa_core.domain import TemplateDomain
from rasa_core.nlg import TemplatedNaturalLanguageGenerator
from rasa_core.trackers import DialogueStateTracker

def test_dispatcher_utter_attachment(default_dispatcher_collecting):
    default_dispatcher_collecting.utter_attachment("http://my-attachment")
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert {'recipient_id': 'my-sender',
            'text': 'Image: http://my-attachment'} == collected

def test_dispatcher_utter_template(default_dispatcher_collecting,
                                   default_tracker):
    default_dispatcher_collecting.utter_template("utter_goodbye",
                                                 default_tracker)
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert collected['text'] in {"goodbye 😢", "bye bye 😢"}

def test_dispatcher_handle_unknown_template(default_dispatcher_collecting,
                                            default_tracker):
    default_dispatcher_collecting.utter_template("my_made_up_template",
                                                 default_tracker)
    collected = default_dispatcher_collecting.output_channel.latest_output()
    assert collected['text'].startswith("Undefined utter template")

def test_dispatcher_template_invalid_vars():
    templates = {
                "my_made_up_template": [{
                    "text": "a template referencing an invalid {variable}."}]}
    bot = CollectingOutputChannel()
    nlg = TemplatedNaturalLanguageGenerator(templates)
    dispatcher = Dispatcher("my-sender", bot, nlg)
    tracker = DialogueStateTracker("my-sender", slots=[])
    dispatcher.utter_template("my_made_up_template", tracker)
    collected = dispatcher.output_channel.latest_output()
    assert collected['text'].startswith(
            "a template referencing an invalid {variable}.")

def test_dispatcher_utter_response(default_dispatcher_collecting):
    text_only_message = {"text": "hey"}
    image_only_message = {"image": "https://i.imgur.com/nGF1K8f.jpg"}
    text_and_image_message = {
        "text": "look at this",
        "image": "https://i.imgur.com/T5xVo.jpg"
    }

    default_dispatcher_collecting.utter_response(text_only_message)
    default_dispatcher_collecting.utter_response(image_only_message)
    default_dispatcher_collecting.utter_response(text_and_image_message)
    collected = default_dispatcher_collecting.output_channel.messages

    assert len(collected) == 4

    # text only message
    assert collected[0] == {
        "recipient_id": "my-sender",
        "text": "hey"}

    # image only message
    assert collected[1] == {
        "recipient_id": "my-sender",
        "text": "Image: https://i.imgur.com/nGF1K8f.jpg"}

    # text & image combined - will result in two messages
    assert collected[2] == {
        "recipient_id": "my-sender",
        "text": "look at this"}
    assert collected[3] == {
        "recipient_id": "my-sender",
        "text": "Image: https://i.imgur.com/T5xVo.jpg"}

def test_dispatcher_utter_buttons(default_dispatcher_collecting):
    buttons = [
        Button(title="Btn1", payload="/btn1"),
        Button(title="Btn2", payload="/btn2")
    ]
    default_dispatcher_collecting.utter_button_message("my message", buttons)
    collected = default_dispatcher_collecting.output_channel.messages
    assert len(collected) == 1
    assert collected[0]['text'] == "my message"
    assert collected[0]['data'] == [
        {'payload': u'/btn1', 'title': u'Btn1'},
        {'payload': u'/btn2', 'title': u'Btn2'}
    ]

def test_dispatcher_utter_buttons_from_domain_templ(default_tracker):
    domain_file = "examples/moodbot/domain.yml"
    domain = TemplateDomain.load(domain_file)
    bot = CollectingOutputChannel()
    nlg = TemplatedNaturalLanguageGenerator(domain.templates)
    dispatcher = Dispatcher("my-sender", bot, nlg)
    dispatcher.utter_template("utter_greet", default_tracker)
    assert len(bot.messages) == 1
    assert bot.messages[0]['text'] == "Hey! How are you?"
    assert bot.messages[0]['data'] == [
        {'payload': 'great', 'title': 'great'},
        {'payload': 'super sad', 'title': 'super sad'}
    ]

def test_dispatcher_utter_custom_message(default_dispatcher_collecting):
    elements = [
        Element(title="hey there", subtitle="welcome", buttons=[
            Button(title="Btn1", payload="/btn1"),
            Button(title="Btn2", payload="/btn2")]),
        Element(title="another title", subtitle="another subtitle", buttons=[
            Button(title="Btn3", payload="/btn3"),
            Button(title="Btn4", payload="/btn4")])
    ]
    default_dispatcher_collecting.utter_custom_message(*elements)
    collected = default_dispatcher_collecting.output_channel.messages
    assert len(collected) == 2
    assert collected[0]['text'] == "hey there : welcome"
    assert collected[0]['data'] == [
        {'payload': u'/btn1', 'title': u'Btn1'},
        {'payload': u'/btn2', 'title': u'Btn2'}
    ]
    assert collected[1]['text'] == "another title : another subtitle"
    assert collected[1]['data'] == [
        {'payload': u'/btn3', 'title': u'Btn3'},
        {'payload': u'/btn4', 'title': u'Btn4'}
    ]
<|endoftext|>


<commit_before> # coding=utf-8
from __future__ import print_function

from nose.tools import *
from .utils import *
from unittest import TestCase
try:
    from unittest import mock
except ImportError:
    import mock

import subprocess

import scuba.dockerutil as uut

class TestDockerutil(TestCase):
    def test_get_image_command_success(self):
        '''get_image_command works'''
        assert_true(uut.get_image_command('debian:8.2'))

    def test_get_image_command_bad_image(self):
        '''get_image_command raises an exception for a bad image name'''
        assert_raises(uut.DockerError, uut.get_image_command, 'nosuchimageZZZZZZZZ')

    def test_get_image_no_docker(self):
        '''get_image_command raises an exception if docker is not installed'''

        real_Popen = subprocess.Popen
        def mocked_popen(popen_args, *args, **kw):
            assert_equal(popen_args[0], 'docker')
            popen_args[0] = 'dockerZZZZ'
            return real_Popen(popen_args, *args, **kw)

        with mock.patch('subprocess.Popen', side_effect=mocked_popen) as popen_mock:
            assert_raises(uut.DockerError, uut.get_image_command, 'n/a')

    def test_make_vol_opt_no_opts(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir'),
                '--volume=/hostdir:/contdir'
                )

    def test_make_vol_opt_one_opt(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir', 'ro'),
                '--volume=/hostdir:/contdir:ro'
                )

    def test_make_vol_opt_multi_opts(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir', ['ro', 'z']),
                '--volume=/hostdir:/contdir:ro,z'
                )
<commit_msg>test: Add test__get_image_command__pulls_image_if_missing<commit_after> # coding=utf-8
from __future__ import print_function

from nose.tools import *
from .utils import *
from unittest import TestCase
try:
    from unittest import mock
except ImportError:
    import mock

import subprocess

import scuba.dockerutil as uut

class TestDockerutil(TestCase):
    def test_get_image_command_success(self):
        '''get_image_command works'''
        assert_true(uut.get_image_command('debian:8.2'))

    def test_get_image_command_bad_image(self):
        '''get_image_command raises an exception for a bad image name'''
        assert_raises(uut.DockerError, uut.get_image_command, 'nosuchimageZZZZZZZZ')

    def test_get_image_no_docker(self):
        '''get_image_command raises an exception if docker is not installed'''

        real_Popen = subprocess.Popen
        def mocked_popen(popen_args, *args, **kw):
            assert_equal(popen_args[0], 'docker')
            popen_args[0] = 'dockerZZZZ'
            return real_Popen(popen_args, *args, **kw)

        with mock.patch('subprocess.Popen', side_effect=mocked_popen) as popen_mock:
            assert_raises(uut.DockerError, uut.get_image_command, 'n/a')

    def test__get_image_command__pulls_image_if_missing(self):
        '''get_image_command pulls an image if missing'''
        image = 'busybox:latest'

        # First remove the image
        subprocess.call(['docker', 'rmi', image])

        # Now try to get the image's Command
        result = uut.get_image_command(image)

        # Should return a non-empty string
        self.assertTrue(result)

    def test_make_vol_opt_no_opts(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir'),
                '--volume=/hostdir:/contdir'
                )

    def test_make_vol_opt_one_opt(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir', 'ro'),
                '--volume=/hostdir:/contdir:ro'
                )

    def test_make_vol_opt_multi_opts(self):
        assert_equal(
                uut.make_vol_opt('/hostdir', '/contdir', ['ro', 'z']),
                '--volume=/hostdir:/contdir:ro,z'
                )
<|endoftext|>


<commit_before>from __future__ import print_function

import numpy as np
import pandas as pd

import numpy.testing as npt
import pytest

import lifetimes.estimation as estimation
from lifetimes.datasets import load_cdnow

cdnow_customers = load_cdnow()

class TestParetoNBDFitter():

    def test_sum_of_scalar_inputs_to_negative_log_likelihood_is_equal_to_array(self):
        ptf = estimation.ParetoNBDFitter
        x = np.array([1,3])
        t_x = np.array([2,2])
        t = np.array([5,6])
        params = [1,1,1,1]
        assert ptf()._negative_log_likelihood(params, np.array([x[0]]), np.array([t_x[0]]), np.array([t[0]]), 0) \
             + ptf()._negative_log_likelihood(params, np.array([x[1]]), np.array([t_x[1]]), np.array([t[1]]), 0) \
            == ptf()._negative_log_likelihood(params, x, t_x, t, 0)

    def test_params_out_is_close_to_Hardie_paper(self):
        ptf = estimation.ParetoNBDFitter()
        ptf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=1)
        expected = np.array([ 0.553, 10.578, 0.606, 11.669])
        npt.assert_array_almost_equal(expected, np.array(ptf._unload_params('r', 'alpha', 's', 'beta')), decimal=3)

    def test_conditional_probability_alive_is_between_0_and_1(self):
        ptf = estimation.ParetoNBDFitter()
        ptf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        for i in range(0, 100, 10):
            for j in range(0, 100, 10):
                for k in range(j, 100, 10):
                    assert 0 <= ptf.conditional_probability_alive(i, j, k) <= 1.0

class TestBetaGammaFitter():

    def test_sum_of_scalar_inputs_to_negative_log_likelihood_is_equal_to_array(self):
        bgf = estimation.BetaGeoFitter
        x = np.array([1,3])
        t_x = np.array([2,2])
        t = np.array([5,6])
        params = [1,1,1,1]
        assert bgf._negative_log_likelihood(params, np.array([x[0]]), np.array([t_x[0]]), np.array([t[0]]), 0) \
             + bgf._negative_log_likelihood(params, np.array([x[1]]), np.array([t_x[1]]), np.array([t[1]]), 0) \
            == bgf._negative_log_likelihood(params, x, t_x, t, 0)

    def test_params_out_is_close_to_Hardie_paper(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=2)
        expected = np.array([0.243, 4.414, 0.793, 2.426])
        npt.assert_array_almost_equal(expected, np.array(bfg._unload_params('r', 'alpha', 'a', 'b')), decimal=3)

    def test_conditional_expectation_returns_same_value_as_Hardie_excel_sheet(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        x = 2
        t_x = 30.43
        T = 38.86
        t = 39
        expected = 1.226
        actual = bfg.conditional_expected_number_of_purchases_up_to_time(t, x, t_x, T)
        assert abs(expected - actual) < 0.001

    def test_expectation_returns_same_value_Hardie_excel_sheet(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        times = np.array([0.1429, 1.0, 3.00, 31.8571, 32.00, 78.00])
        expected = np.array([0.0078 ,0.0532 ,0.1506 ,1.0405,1.0437, 1.8576])
        actual = bfg.expected_number_of_purchases_up_to_time(times)
        npt.assert_array_almost_equal(actual, expected, decimal=3)

    def test_conditional_probability_alive_returns_1_if_no_repeat_purchases(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        assert bfg.conditional_probability_alive(0, 1, 1) == 1.0

    def test_conditional_probability_alive_is_between_0_and_1(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        for i in range(0, 100, 10):
            for j in range(0, 100, 10):
                for k in range(j, 100, 10):
                    assert 0 <= bfg.conditional_probability_alive(i, j, k) <= 1.0

    def test_fit_method_allows_for_better_accuracy_by_using_iterative_fitting(self):
        bfg1 = estimation.BetaGeoFitter()
        bfg2 = estimation.BetaGeoFitter()

        np.random.seed(0)
        bfg1.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        np.random.seed(0)
        bfg2.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=5)
        assert bfg1._negative_log_likelihood_ >= bfg2._negative_log_likelihood_

    def test_penalizer_term_will_shrink_coefs_to_0(self):
        bfg_no_penalizer = estimation.BetaGeoFitter()
        bfg_no_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_1 = np.array(list(bfg_no_penalizer.params_.values()))

        bfg_with_penalizer = estimation.BetaGeoFitter(penalizer_coef=0.1)
        bfg_with_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_2 = np.array(list(bfg_with_penalizer.params_.values()))
        assert np.all(params_2 < params_1)

        bfg_with_more_penalizer = estimation.BetaGeoFitter(penalizer_coef=10)
        bfg_with_more_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_3 = np.array(list(bfg_with_more_penalizer.params_.values()))
        assert np.all(params_3 < params_2)

    def test_conditional_probability_alive_matrix(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        Z = bfg.conditional_probability_alive_matrix()
        max_t = int(bfg.data['T'].max())
        assert Z[0][0] == 1

        for t_x in range(Z.shape[0]):
            for x in range(Z.shape[1]):
                assert Z[t_x][x] == bfg.conditional_probability_alive(x, t_x, max_t)

    def test_scaling_inputs_gives_same_or_similar_results(self):
        bgf = estimation.BetaGeoFitter()
        bgf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        scale = 10
        bgf_with_large_inputs = estimation.BetaGeoFitter()
        bgf_with_large_inputs.fit(cdnow_customers['frequency'], scale*cdnow_customers['recency'], scale*cdnow_customers['T'])
        assert bgf_with_large_inputs._scale < 1.

        assert abs(bgf_with_large_inputs.conditional_probability_alive(1, 1, 2) - bgf.conditional_probability_alive(1, 1, 2)) < 10e-5
        assert abs(bgf_with_large_inputs.conditional_probability_alive(1, 2, 10) == bgf.conditional_probability_alive(1, 2, 10)) < 10e-5

<commit_msg>make that test oh so sweet<commit_after>from __future__ import print_function

import numpy as np
import pandas as pd

import numpy.testing as npt
import pytest

import lifetimes.estimation as estimation
from lifetimes.datasets import load_cdnow

cdnow_customers = load_cdnow()

class TestParetoNBDFitter():

    def test_sum_of_scalar_inputs_to_negative_log_likelihood_is_equal_to_array(self):
        ptf = estimation.ParetoNBDFitter
        x = np.array([1,3])
        t_x = np.array([2,2])
        t = np.array([5,6])
        params = [1,1,1,1]
        assert ptf()._negative_log_likelihood(params, np.array([x[0]]), np.array([t_x[0]]), np.array([t[0]]), 0) \
             + ptf()._negative_log_likelihood(params, np.array([x[1]]), np.array([t_x[1]]), np.array([t[1]]), 0) \
            == ptf()._negative_log_likelihood(params, x, t_x, t, 0)

    def test_params_out_is_close_to_Hardie_paper(self):
        ptf = estimation.ParetoNBDFitter()
        ptf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=1)
        expected = np.array([ 0.553, 10.578, 0.606, 11.669])
        npt.assert_array_almost_equal(expected, np.array(ptf._unload_params('r', 'alpha', 's', 'beta')), decimal=3)

    def test_conditional_probability_alive_is_between_0_and_1(self):
        ptf = estimation.ParetoNBDFitter()
        ptf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        for i in range(0, 100, 10):
            for j in range(0, 100, 10):
                for k in range(j, 100, 10):
                    assert 0 <= ptf.conditional_probability_alive(i, j, k) <= 1.0

class TestBetaGammaFitter():

    def test_sum_of_scalar_inputs_to_negative_log_likelihood_is_equal_to_array(self):
        bgf = estimation.BetaGeoFitter
        x = np.array([1,3])
        t_x = np.array([2,2])
        t = np.array([5,6])
        params = [1,1,1,1]
        assert bgf._negative_log_likelihood(params, np.array([x[0]]), np.array([t_x[0]]), np.array([t[0]]), 0) \
             + bgf._negative_log_likelihood(params, np.array([x[1]]), np.array([t_x[1]]), np.array([t[1]]), 0) \
            == bgf._negative_log_likelihood(params, x, t_x, t, 0)

    def test_params_out_is_close_to_Hardie_paper(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=2)
        expected = np.array([0.243, 4.414, 0.793, 2.426])
        npt.assert_array_almost_equal(expected, np.array(bfg._unload_params('r', 'alpha', 'a', 'b')), decimal=3)

    def test_conditional_expectation_returns_same_value_as_Hardie_excel_sheet(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        x = 2
        t_x = 30.43
        T = 38.86
        t = 39
        expected = 1.226
        actual = bfg.conditional_expected_number_of_purchases_up_to_time(t, x, t_x, T)
        assert abs(expected - actual) < 0.001

    def test_expectation_returns_same_value_Hardie_excel_sheet(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        times = np.array([0.1429, 1.0, 3.00, 31.8571, 32.00, 78.00])
        expected = np.array([0.0078 ,0.0532 ,0.1506 ,1.0405,1.0437, 1.8576])
        actual = bfg.expected_number_of_purchases_up_to_time(times)
        npt.assert_array_almost_equal(actual, expected, decimal=3)

    def test_conditional_probability_alive_returns_1_if_no_repeat_purchases(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        assert bfg.conditional_probability_alive(0, 1, 1) == 1.0

    def test_conditional_probability_alive_is_between_0_and_1(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        for i in range(0, 100, 10):
            for j in range(0, 100, 10):
                for k in range(j, 100, 10):
                    assert 0 <= bfg.conditional_probability_alive(i, j, k) <= 1.0

    def test_fit_method_allows_for_better_accuracy_by_using_iterative_fitting(self):
        bfg1 = estimation.BetaGeoFitter()
        bfg2 = estimation.BetaGeoFitter()

        np.random.seed(0)
        bfg1.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        np.random.seed(0)
        bfg2.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'], iterative_fitting=5)
        assert bfg1._negative_log_likelihood_ >= bfg2._negative_log_likelihood_

    def test_penalizer_term_will_shrink_coefs_to_0(self):
        bfg_no_penalizer = estimation.BetaGeoFitter()
        bfg_no_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_1 = np.array(list(bfg_no_penalizer.params_.values()))

        bfg_with_penalizer = estimation.BetaGeoFitter(penalizer_coef=0.1)
        bfg_with_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_2 = np.array(list(bfg_with_penalizer.params_.values()))
        assert np.all(params_2 < params_1)

        bfg_with_more_penalizer = estimation.BetaGeoFitter(penalizer_coef=10)
        bfg_with_more_penalizer.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        params_3 = np.array(list(bfg_with_more_penalizer.params_.values()))
        assert np.all(params_3 < params_2)

    def test_conditional_probability_alive_matrix(self):
        bfg = estimation.BetaGeoFitter()
        bfg.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])
        Z = bfg.conditional_probability_alive_matrix()
        max_t = int(bfg.data['T'].max())
        assert Z[0][0] == 1

        for t_x in range(Z.shape[0]):
            for x in range(Z.shape[1]):
                assert Z[t_x][x] == bfg.conditional_probability_alive(x, t_x, max_t)

    def test_scaling_inputs_gives_same_or_similar_results(self):
        bgf = estimation.BetaGeoFitter()
        bgf.fit(cdnow_customers['frequency'], cdnow_customers['recency'], cdnow_customers['T'])

        scale = 10
        bgf_with_large_inputs = estimation.BetaGeoFitter()
        bgf_with_large_inputs.fit(cdnow_customers['frequency'], scale*cdnow_customers['recency'], scale*cdnow_customers['T'])
        assert bgf_with_large_inputs._scale < 1.

        assert abs(bgf_with_large_inputs.conditional_probability_alive(1, scale*1, scale*2) - bgf.conditional_probability_alive(1, 1, 2)) < 10e-5
        assert abs(bgf_with_large_inputs.conditional_probability_alive(1, scale*2, scale*10) - bgf.conditional_probability_alive(1, 2, 10)) < 10e-5

<|endoftext|>


<commit_before>#!/usr/bin/env python3
# Written by Daniel Oaks <daniel@danieloaks.net>
# Released under the ISC license
import unittest

import base
from girc import formatting

class FormattingTestCase(unittest.TestCase):
    """Tests our formatting."""

    def setUp(self):
        errmsg = 'formatting.{} does not exist!'
        self.assertTrue(formatting.escape, msg=errmsg.format('escape'))
        self.assertTrue(formatting.unescape, msg=errmsg.format('unescape'))

    def test_colour_codes(self):
        self.assertEqual(formatting._ctos(5), 'brown')
        self.assertEqual(formatting._ctos(452), 'unknown: 452')

    def test_escaping(self):
        self.assertEqual(formatting.escape('Strawberries are \x02cool\x0f'),
                         'Strawberries are $bcool$r')

        self.assertEqual(formatting.escape('Such \x1dcool\x1d things\x02!\x0f'),
                         'Such $icool$i things$b!$r')

        self.assertEqual(formatting.escape('Lol \x03cool \x032tests\x0f!'),
                         'Lol $c[]cool $c[blue]tests$r!')

        self.assertEqual(formatting.escape('Lol cool\x03'),
                         'Lol cool$c[]')

        self.assertEqual(formatting.escape('Lol \x034cool \x032,tests\x0f!'),
                         'Lol $c[red]cool $c[blue],tests$r!')

        self.assertEqual(formatting.escape('\x02Lol \x034,2cool \x033,8tests\x0f!'),
                         '$bLol $c[red,blue]cool $c[green,yellow]tests$r!')

    def test_unescaping(self):
        self.assertEqual(formatting.unescape('Strawberries are $$cool$r'),
                         'Strawberries are $cool\x0f')

        self.assertEqual(formatting.unescape('Strawberries are $bcool$r'),
                         'Strawberries are \x02cool\x0f')

        self.assertEqual(formatting.unescape('Such $icool$i things$b!$r'),
                         'Such \x1dcool\x1d things\x02!\x0f')

        self.assertEqual(formatting.unescape('How cool$c'),
                         'How cool\x03')

        self.assertEqual(formatting.unescape('Lol $c[red]cool $c[blue]tests$r!'),
                         'Lol \x034cool \x032tests\x0f!')

        self.assertEqual(formatting.unescape('$bLol $c[red,blue]cool $c[green,yellow]tests$r!'),
                         '\x02Lol \x034,2cool \x033,8tests\x0f!')
<commit_msg>tests: Improve formatting coverage<commit_after>#!/usr/bin/env python3
# Written by Daniel Oaks <daniel@danieloaks.net>
# Released under the ISC license
import unittest

import base
from girc import formatting

class FormattingTestCase(unittest.TestCase):
    """Tests our formatting."""

    def setUp(self):
        errmsg = 'formatting.{} does not exist!'
        self.assertTrue(formatting.escape, msg=errmsg.format('escape'))
        self.assertTrue(formatting.unescape, msg=errmsg.format('unescape'))

    def test_colour_codes(self):
        self.assertEqual(formatting._ctos(5), 'brown')
        self.assertEqual(formatting._ctos(452), 'unknown: 452')

    def test_escaping(self):
        self.assertEqual(formatting.escape('Strawberries are \x02cool\x0f'),
                         'Strawberries are $bcool$r')

        self.assertEqual(formatting.escape('Such \x1dcool\x1d things\x02!\x0f'),
                         'Such $icool$i things$b!$r')

        self.assertEqual(formatting.escape('Lol \x03cool \x032tests\x0f!'),
                         'Lol $c[]cool $c[blue]tests$r!')

        self.assertEqual(formatting.escape('Lol cool\x03'),
                         'Lol cool$c[]')

        self.assertEqual(formatting.escape('Lol \x034cool \x032,tests\x0f!'),
                         'Lol $c[red]cool $c[blue],tests$r!')

        self.assertEqual(formatting.escape('\x02Lol \x034,2cool \x033,8tests\x0f!'),
                         '$bLol $c[red,blue]cool $c[green,yellow]tests$r!')

    def test_unescaping(self):
        self.assertEqual(formatting.unescape('Strawberries are $$cool$r'),
                         'Strawberries are $cool\x0f')

        self.assertEqual(formatting.unescape('Strawberries are $bcool$r'),
                         'Strawberries are \x02cool\x0f')

        self.assertEqual(formatting.unescape('Such $icool$i things$b!$r'),
                         'Such \x1dcool\x1d things\x02!\x0f')

        self.assertEqual(formatting.unescape('How cool$c'),
                         'How cool\x03')

        self.assertEqual(formatting.unescape('Lol $c[red]cool $c[blue]tests$r!'),
                         'Lol \x034cool \x032tests\x0f!')

        self.assertEqual(formatting.unescape('$bLol $c[red,blue]cool $c[green,yellow]tests$r!'),
                         '\x02Lol \x034,2cool \x033,8tests\x0f!')

        # testing custom unescaping function
        def custom_unescape(*args, **kwargs):
            return '{}-{}'.format(','.join(args),
                                  ','.join('{}:{}'.format(k, v) for k, v in kwargs.items()))

        extra_dict = {
            'custom': [custom_unescape, ['r', 't'], {'34': 'dfg'}],
        }
        self.assertEqual(formatting.unescape('lolo[${custom}]', extra_format_dict=extra_dict),
                         'lolo[r,t-34:dfg]')

        extra_dict = {
            'custom': [custom_unescape, ['wer', 'hgd']],
        }
        self.assertEqual(formatting.unescape('fff--${custom}]', extra_format_dict=extra_dict),
                         'fff--wer,hgd-]')

        extra_dict = {
            'custom': [custom_unescape],
        }
        self.assertEqual(formatting.unescape('abcd=${custom}=', extra_format_dict=extra_dict),
                         'abcd=-=')
<|endoftext|>


<commit_before># MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.

import pytest

pytestmark = pytest.mark.asyncio

async def test_redirection(get_version):
    assert await get_version("jmeter-plugins-manager", {
        "source": "httpheader",
        "url": "https://www.unifiedremote.com/download/linux-x64-deb",
        "regex": r'urserver-([\d.]+).deb',
    }) != None

<commit_msg>Correct package name in httpheader test<commit_after># MIT licensed
# Copyright (c) 2021 lilydjwg <lilydjwg@gmail.com>, et al.

import pytest

pytestmark = pytest.mark.asyncio

async def test_redirection(get_version):
    assert await get_version("unifiedremote", {
        "source": "httpheader",
        "url": "https://www.unifiedremote.com/download/linux-x64-deb",
        "regex": r'urserver-([\d.]+).deb',
    }) != None

<|endoftext|>


<commit_before>import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from SATSolver.individual import Individual
from BitVector import BitVector
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9, Individual.BIT_VECTOR)

        # BitVector implementation

        ind.data = BitVector(bitlist=[0, 1, 1, 0, 1, 0, 1, 0, 0])
        ind.method = Individual.BIT_VECTOR
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

        # bittarray implementation

        ind.data = bitarray("011010100")
        ind.method = Individual.BIT_ARRAY
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9, Individual.BIT_VECTOR)

        ind.data = BitVector(bitlist=[0, 1, 1, 0, 1, 0, 1, 0, 0])
        ind.method = Individual.BIT_VECTOR
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

        # bittarray implementation

        ind.data = bitarray("011010100")
        ind.method = Individual.BIT_ARRAY
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9, Individual.BIT_VECTOR)

        # BitVector implementation

        ind.data = BitVector(bitlist=[0, 1, 1, 0, 1, 0, 1, 0, 0])
        ind.method = Individual.BIT_VECTOR
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

        # bittarray implementation

        ind.data = bitarray("011010100")
        ind.method = Individual.BIT_ARRAY
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

    def test_set_defined(self):
        ind = Individual(9, Individual.BIT_VECTOR)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), False)
        for x in range(1, 10):
            ind.set_defined(x)
            self.assertEqual(ind.get_defined(x), True)

    def test_get_defined(self):
        ind = Individual(9, Individual.BIT_VECTOR)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), False)
        for x in range(1, 10):
            ind.set_defined(x)
            self.assertEqual(ind.get_defined(x), True)

    def test_allocate(self):
        ind = Individual(9, Individual.BIT_VECTOR)
        ind.allocate(ind, ind)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), True)
<commit_msg>Updated tests<commit_after>import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from SATSolver.individual import Individual
from BitVector import BitVector
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

    def test_set_defined(self):
        ind = Individual(9)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), False)
        for x in range(1, 10):
            ind.set_defined(x)
            self.assertEqual(ind.get_defined(x), True)

    def test_get_defined(self):
        ind = Individual(9)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), False)
        for x in range(1, 10):
            ind.set_defined(x)
            self.assertEqual(ind.get_defined(x), True)

    def test_allocate(self):
        ind = Individual(9)
        ind.allocate(ind, ind)
        for x in range(1, 10):
            self.assertEqual(ind.get_defined(x), True)
<|endoftext|>


<commit_before>__author__ = 'dankle'

import unittest
import subprocess

from mock import MagicMock, patch
from localq.Status import Status

from localq.Job import Job

class TestJob(unittest.TestCase):

    unique_job_id = 0
    job = None

    def setUp(self):
        self.unique_job_id += 1
        cmd = ["ls", "-la"]
        self.job = Job(self.unique_job_id, cmd)

    def test__hash__(self):
        self.assertEqual(self.unique_job_id, self.job.__hash__())

    def test___init__(self):
        # only check name is correctly set if no name specified.
        self.assertEqual(self.job.name, "localq-" + str(self.unique_job_id))

    def test___str__(self):
        expected = str(self.job.jobid) + "-" + str(self.job.name)
        self.assertEqual(expected, self.job.__str__())

    def test_info(self):
        expected = "\t".join(
            [str(self.job.jobid),
             str(self.job.priority()),
             str(self.job.status()),
             str(self.job.num_cores),
             str(self.job.start_time),
             str(self.job.end_time),
             str(self.job.name),
             str(" ".join(self.job.cmd))]
        )
        self.assertEqual(expected, self.job.info())

    def test_kill(self):
        self.job.proc = MagicMock()
        self.job.kill()
        self.job.proc.kill.assert_called_with()
        assert self.job._status == Status.CANCELLED

        self.job.proc.kill = MagicMock(side_effect=OSError("foo"))
        self.job.kill()
        self.job.proc.kill.assert_called_with()
        assert self.job._status == Status.CANCELLED

    def test_priority(self):
        self.assertEqual(-1 * self.unique_job_id, self.job.priority())

    def test_run(self):
        with patch.object(subprocess, "Popen", return_value="Fake process"):
            # Should just run without trouble.
            self.job.run()
            assert self.job.proc == "Fake process"
        # if an exception is thrown, make sure it's handled.
        with patch.object(subprocess, "Popen", side_effect=OSError("foo")):
            self.job.run()
            assert self.job.proc == None
            assert self.job._failed_to_start

    def test_status(self):
        with patch.object(Job, "update_status", return_value=None) as mock_update_status:
            actual_status = self.job.status()
            mock_update_status.assert_called_with()
            assert self.job._status == actual_status

    def test_update_status(self):
        mock_proc = MagicMock(returncode=None)
        self.job.proc = mock_proc

        self.job._status = Status.CANCELLED
        self.job.update_status()
        assert self.job._status == Status.CANCELLED

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=None)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.RUNNING

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=-1)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.CANCELLED

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=1)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.FAILED

        self.job.proc = False
        self.job.update_status()
        assert self.job._status == Status.PENDING

        self.job._failed_to_start = True
        self.job.update_status()
        assert self.job._status == Status.FAILED

    if __name__ == '__main__':
        unittest.main()<commit_msg>fixed tests<commit_after>__author__ = 'dankle'

import unittest
import subprocess

from mock import MagicMock, patch
from localq.Status import Status

from localq.Job import Job

class TestJob(unittest.TestCase):

    unique_job_id = 0
    job = None

    def setUp(self):
        self.unique_job_id += 1
        cmd = ["ls", "-la"]
        self.job = Job(self.unique_job_id, cmd)

    def test__hash__(self):
        self.assertEqual(self.unique_job_id, self.job.__hash__())

    def test___init__(self):
        # only check name is correctly set if no name specified.
        self.assertEqual(self.job.name, "localq-" + str(self.unique_job_id))

    def test___str__(self):
        expected = str(self.job.jobid) + "-" + str(self.job.name)
        self.assertEqual(expected, self.job.__str__())

    def test_info(self):
        expected = "\t".join(
            [str(self.job.jobid),
             str(self.job.priority()),
             str(self.job.status()),
             str(self.job.num_cores),
             str(self.job.start_time),
             str(self.job.end_time),
             str(self.job.name),
             str(" ".join(self.job.cmd))]
        )
        self.assertEqual(expected, self.job.info())

    def test_kill(self):
        self.job.proc = MagicMock()
        self.job.kill()
        self.job.proc.terminate.assert_called_with()
        assert self.job._status == Status.CANCELLED

        self.job.proc.kill = MagicMock(side_effect=OSError("foo"))
        self.job.kill()
        self.job.proc.terminate.assert_called_with()
        assert self.job._status == Status.CANCELLED

    def test_priority(self):
        self.assertEqual(-1 * self.unique_job_id, self.job.priority())

    def test_run(self):
        with patch.object(subprocess, "Popen", return_value="Fake process"):
            # Should just run without trouble.
            self.job.run()
            assert self.job.proc == "Fake process"
        # if an exception is thrown, make sure it's handled.
        with patch.object(subprocess, "Popen", side_effect=OSError("foo")):
            self.job.run()
            assert self.job.proc == None
            assert self.job._failed_to_start

    def test_status(self):
        with patch.object(Job, "update_status", return_value=None) as mock_update_status:
            actual_status = self.job.status()
            mock_update_status.assert_called_with()
            assert self.job._status == actual_status

    def test_update_status(self):
        mock_proc = MagicMock(returncode=None)
        self.job.proc = mock_proc

        self.job._status = Status.CANCELLED
        self.job.update_status()
        assert self.job._status == Status.CANCELLED

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=None)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.RUNNING

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=-1)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.CANCELLED

        self.job._status = Status.RUNNING
        mock_proc = MagicMock(returncode=1)
        self.job.proc = mock_proc
        self.job.update_status()
        assert self.job._status == Status.FAILED

        self.job.proc = False
        self.job.update_status()
        assert self.job._status == Status.PENDING

        self.job._failed_to_start = True
        self.job.update_status()
        assert self.job._status == Status.FAILED

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


<commit_before>from simulocloud import PointCloud
import pytest
import numpy as np
import cPickle as pkl
import os

""" Test data """

@pytest.fixture
def input_list():
    """Simple [xs, ys, zs] coordinates."""
    return [[10.0, 12.2, 14.4, 16.6, 18.8],
            [11.1, 13.3, 15.5, 17.7, 19.9],
            [0.1, 2.1, 4.5, 6.7, 8.9]]

@pytest.fixture
def expected_list_points():
    """The points array that should be generated from `input_list`."""
    return np.array([( 10. ,  11.1,  0.1),
                     ( 12.2,  13.3,  2.1),
                     ( 14.4,  15.5,  4.5),
                     ( 16.6,  17.7,  6.7),
                     ( 18.8,  19.9,  8.9)],
                    dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])

@pytest.fixture
def expected_las_points(fname='ALS_points.pkl'):
    """The points array that should be generated from the example las data."""
    with open(abspath(fname), 'rb') as o:
        points = pkl.load(o)
    return points

""" Helper functions """

def abspath(fname, fdir='data'):
    """Return the absolute filepath of filename in (relative) directory."""
    return os.path.join(os.path.dirname(__file__), fdir, fname)

""" Test functions """

def test_PointCloud_read_directly_from_list(input_list, expected_list_points):
    """Can PointCloud initialise directly from `[xs, ys, zs]` ?"""
    assert np.all(PointCloud(input_list).points == expected_list_points)

def test_PointCloud_read_from_las(expected_las_points, fname='ALS.las'):
    """Can PointCloud be constructed from a `.las` file?"""
    assert np.all(PointCloud.from_las(abspath(fname)).points == expected_las_points)
<commit_msg>Use list data which are easier to read<commit_after>from simulocloud import PointCloud
import pytest
import numpy as np
import cPickle as pkl
import os

""" Test data """
# Data type used for arrays
_DTYPE = np.float64

@pytest.fixture
def input_list():
    """Simple [xs, ys, zs] coordinates."""
    return [[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
            [1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9],
            [2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9]]

@pytest.fixture
def expected_list_points():
    """The points array that should be generated from `input_list`."""
    return np.array([( 0. ,  1. ,  2. ),
                    ( 0.1,  1.1,  2.1),
                    ( 0.2,  1.2,  2.2),
                    ( 0.3,  1.3,  2.3),
                    ( 0.4,  1.4,  2.4),
                    ( 0.5,  1.5,  2.5),
                    ( 0.6,  1.6,  2.6),
                    ( 0.7,  1.7,  2.7),
                    ( 0.8,  1.8,  2.8),
                    ( 0.9,  1.9,  2.9)],
                   dtype=[('x', _DTYPE), ('y', _DTYPE), ('z', _DTYPE)])

@pytest.fixture
def expected_las_points(fname='ALS_points.pkl'):
    """The points array that should be generated from the example las data."""
    with open(abspath(fname), 'rb') as o:
        points = pkl.load(o)
    return points

""" Helper functions """

def abspath(fname, fdir='data'):
    """Return the absolute filepath of filename in (relative) directory."""
    return os.path.join(os.path.dirname(__file__), fdir, fname)

""" Test functions """

def test_PointCloud_read_directly_from_list(input_list, expected_list_points):
    """Can PointCloud initialise directly from `[xs, ys, zs]` ?"""
    assert np.all(PointCloud(input_list).points == expected_list_points)

def test_PointCloud_read_from_las(expected_las_points, fname='ALS.las'):
    """Can PointCloud be constructed from a `.las` file?"""
    assert np.all(PointCloud.from_las(abspath(fname)).points == expected_las_points)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import os

import pybel
from pybel.constants import *
from pybel_tools.mutation import prune_central_dogma, infer_missing_inverse_edge, infer_central_dogma
from tests.constants import ManagerMixin

class TestProcessing(ManagerMixin):
    def setUp(self):
        super(TestProcessing, self).setUp()

        if 'PYBEL_BASE' in os.environ:
            test_bel_simple_path = os.path.join(os.environ['PYBEL_BASE'], 'tests', 'bel', 'test_bel.bel')
            self.graph = pybel.from_path(test_bel_simple_path, manager=self.manager)
        else:
            test_bel_simple_url = 'https://raw.githubusercontent.com/pybel/pybel/develop/tests/bel/test_bel.bel'
            self.graph = pybel.from_url(test_bel_simple_url, manager=self.manager)

        infer_central_dogma(self.graph)

        n1 = GENE, 'HGNC', 'AKT1'
        n2 = RNA, 'HGNC', 'EGFR'

        n3 = GENE, 'HGNC', 'DUMMY1'
        self.graph.add_simple_node(*n3)

        n4 = GENE, 'HGNC', 'DUMMY2'
        self.graph.add_simple_node(*n4)

        self.graph.add_edge(n1, n3, **{RELATION: INCREASES})
        self.graph.add_edge(n2, n4, **{RELATION: INCREASES})

    def test_prune(self):
        self.assertEqual(14, self.graph.number_of_nodes())
        self.assertEqual(16, self.graph.number_of_edges())

        prune_central_dogma(self.graph)
        self.assertEqual(9, self.graph.number_of_nodes())

    def test_infer(self):
        self.assertEqual(14, self.graph.number_of_nodes())
        self.assertEqual(16, self.graph.number_of_edges())

        infer_missing_inverse_edge(self.graph, TRANSLATED_TO)
        self.assertEqual(20, self.graph.number_of_edges())
<commit_msg>Fix testing<commit_after># -*- coding: utf-8 -*-

import unittest

from pybel.dsl import gene, rna
from pybel.examples import sialic_acid_graph
from pybel_tools.mutation import infer_central_dogma, prune_central_dogma

trem2_gene = gene(namespace='HGNC', name='TREM2')
trem2_rna = rna(namespace='HGNC', name='TREM2')

class TestProcessing(unittest.TestCase):
    def test_infer_on_sialic_acid_example(self):
        sgc = sialic_acid_graph.copy()

        self.assertFalse(sgc.has_node_with_data(trem2_gene))
        self.assertFalse(sgc.has_node_with_data(trem2_rna))

        infer_central_dogma(sgc)

        self.assertTrue(sgc.has_node_with_data(trem2_gene))
        self.assertTrue(sgc.has_node_with_data(trem2_rna))

        prune_central_dogma(sgc)

        self.assertFalse(sgc.has_node_with_data(trem2_gene))
        self.assertFalse(sgc.has_node_with_data(trem2_rna))
<|endoftext|>