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

import unittest

from . import engine

from sqlalchemy.orm import sessionmaker

class ModelTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.engine = engine

    def setUp(self):
        connection = self.engine.connect()
        self.trans = connection.begin()

        # Setting up SQLAlchemy
        from skosprovider_sqlalchemy.models import Base
        Base.metadata.bind = engine
        sm = sessionmaker(bind=engine)
        self.session = sm()

    def tearDown(self):
        self.session.close()
        self.trans.rollback()

class ConceptTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Concept
        return Concept

    def test_simple(self):
        from ..models import Label
        l = Label('Churches', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

    def test_related(self):
        c1 = self._get_target_class()(
            id=1
        )
        c2 = self._get_target_class()(
            id=2
        )
        c1.related_concepts.append(c2)
        self.session.flush()
        self.assertEqual(1, len(c1.related_concepts))
        self.assertEqual(1, len(c2.related_concepts))
        c2.related_concepts.remove(c1)
        self.assertEqual(0, len(c1.related_concepts))
        self.assertEqual(0, len(c2.related_concepts))

    def test_broader_narrower(self):
        c1 = self._get_target_class()(
            id=1
        )
        c2 = self._get_target_class()(
            id=2
        )
        c1.narrower_concepts.append(c2)
        self.session.flush()
        self.assertEqual(1, len(c1.narrower_concepts))
        self.assertEqual(1, len(c2.broader_concepts))
        c2.broader_concepts.remove(c1)
        self.assertEqual(0, len(c1.narrower_concepts))
        self.assertEqual(0, len(c2.broader_concepts))

class ConceptSchemeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import ConceptScheme
        return ConceptScheme

    def test_simple(self):
        from ..models import Label
        l = Label('Heritage types', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.session.flush()
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

class CollectionTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Collection
        return Collection

    def _get_concept(self):
        from ..models import Concept, Label
        return Concept(
            id=2,
            labels=[Label('Cathedrals', 'prefLabel', 'en')]
        )

    def test_simple(self):
        from ..models import Label
        l = Label('Churches by function', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

    def test_members(self):
        col = self._get_target_class()(
            id=1
        )
        c = self._get_concept()
        col.members.append(c)
        self.session.flush()
        self.assertEqual(1, len(c.collections))
        self.assertEqual(col, c.collections[0])

class LabelTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Label
        return Label

    def test_simple(self):
        l = self._get_target_class()('Kerken', 'prefLabel', 'nl')
        self.assertEqual('nl', l.language_id)
        self.assertEqual('prefLabel', l.labeltype_id)
        self.assertEqual('Kerken', l.__str__())

    def test_load_objects(self):
        l = self._get_target_class()('Kerken', 'prefLabel', 'nl')
        self.session.add(l)
        self.session.flush()
        self.assertEqual('Dutch', l.language.name)
        self.assertEqual('prefLabel', l.labeltype.name)

    def test_no_language(self):
        l = self._get_target_class()('Kerken', 'prefLabel')
        self.assertEqual(None, l.language_id)
        self.assertEqual('prefLabel', l.labeltype_id)
        self.assertEqual('Kerken', l.__str__())
        self.session.add(l)
        self.session.flush()
        self.assertEqual(None, l.language_id)
        self.assertEqual('prefLabel', l.labeltype.name)

class NoteTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Note
        return Note

    def test_simple(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            'nl'
        )
        self.assertEqual('nl', n.language_id)
        self.assertEqual('definition', n.notetype_id)
        self.assertEqual('Een kerk is een religieus gebouw.', n.__str__())

    def test_load_objects(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            'nl'
        )
        self.session.add(n)
        self.session.flush()
        self.assertEqual('Dutch', n.language.name)
        self.assertEqual('definition', n.notetype.name)

    def test_no_language(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            None
        )
        self.assertEqual(None, n.language_id)
        self.assertEqual('definition', n.notetype_id)
        self.assertEqual('Een kerk is een religieus gebouw.', n.__str__())
        self.session.add(n)
        self.session.flush()
        self.assertEqual(None, n.language)
        self.assertEqual('definition', n.notetype.name)

class LanguageTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Language
        return Language

    def test_simple(self):
        l = self._get_target_class()('nl', 'Dutch')
        self.assertEqual('nl', l.id)
        self.assertEqual('Dutch', l.name)
        self.assertEqual('Dutch', l.__str__())

class LabelTypeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import LabelType
        return LabelType

    def test_simple(self):
        l = self._get_target_class()('prefLabel', 'Preferred label')
        self.assertEqual('prefLabel', l.name)
        self.assertEqual('Preferred label', l.description)
        self.assertEqual('prefLabel', l.__str__())

class NoteTypeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import NoteType
        return NoteType

    def test_simple(self):
        n = self._get_target_class()('definition', 'A definition.')
        self.assertEqual('definition', n.name)
        self.assertEqual('A definition.', n.description)
        self.assertEqual('definition', n.__str__())

class LabelFunctionTest(ModelTestCase):

    def _get_fut(self):
        from ..models import label
        return label

    def _get_knokke_heist_nl(self):
        from ..models import Label
        return Label('Knokke-Heist', "prefLabel", 'nl')

    def _get_cnocke_heyst_nl(self):
        from ..models import Label
        return Label('Cnock-Heyst', "altLabel", 'nl')

    def _get_knokke_heist_en(self):
        from ..models import Label
        return Label('Knocke-Heyst', "prefLabel", 'en')

    def test_label_empty(self):
        label = self._get_fut()
        self.assertEqual(None, label([]))
        self.assertEqual(None, label([], 'nl'))
        self.assertEqual(None, label([], None))

    def test_label_pref(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        labels = [kh]
        self.assertEqual(kh, label(labels))
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(kh, label(labels, 'en'))
        self.assertEqual(kh, label(labels, None))

    def test_label_pref_nl_and_en(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        khen = self._get_knokke_heist_en()
        labels = [kh, khen]
        self.assertIn(label(labels), [kh, khen])
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(khen, label(labels, 'en'))
        self.assertIn(label(labels, None), [kh, khen])

    def test_label_alt(self):
        label = self._get_fut()
        ch = self._get_cnocke_heyst_nl()
        labels = [ch]
        self.assertEqual(ch, label(labels))
        self.assertEqual(ch, label(labels, 'nl'))
        self.assertEqual(ch, label(labels, 'en'))
        self.assertEqual(ch, label(labels, None))

    def test_pref_precedes_alt(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        ch = self._get_cnocke_heyst_nl()
        labels = [kh, ch]
        self.assertEqual(kh, label(labels))
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(kh, label(labels, 'en'))
        self.assertEqual(kh, label(labels, None))
<commit_msg>Fix failing python 2.6 unittest.<commit_after># -*- coding: utf-8 -*-

try:
    import unittest2 as unittest
except ImportError:  # pragma NO COVER
    import unittest  # noqa

from . import engine

from sqlalchemy.orm import sessionmaker

class ModelTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.engine = engine

    def setUp(self):
        connection = self.engine.connect()
        self.trans = connection.begin()

        # Setting up SQLAlchemy
        from skosprovider_sqlalchemy.models import Base
        Base.metadata.bind = engine
        sm = sessionmaker(bind=engine)
        self.session = sm()

    def tearDown(self):
        self.session.close()
        self.trans.rollback()

class ConceptTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Concept
        return Concept

    def test_simple(self):
        from ..models import Label
        l = Label('Churches', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

    def test_related(self):
        c1 = self._get_target_class()(
            id=1
        )
        c2 = self._get_target_class()(
            id=2
        )
        c1.related_concepts.append(c2)
        self.session.flush()
        self.assertEqual(1, len(c1.related_concepts))
        self.assertEqual(1, len(c2.related_concepts))
        c2.related_concepts.remove(c1)
        self.assertEqual(0, len(c1.related_concepts))
        self.assertEqual(0, len(c2.related_concepts))

    def test_broader_narrower(self):
        c1 = self._get_target_class()(
            id=1
        )
        c2 = self._get_target_class()(
            id=2
        )
        c1.narrower_concepts.append(c2)
        self.session.flush()
        self.assertEqual(1, len(c1.narrower_concepts))
        self.assertEqual(1, len(c2.broader_concepts))
        c2.broader_concepts.remove(c1)
        self.assertEqual(0, len(c1.narrower_concepts))
        self.assertEqual(0, len(c2.broader_concepts))

class ConceptSchemeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import ConceptScheme
        return ConceptScheme

    def test_simple(self):
        from ..models import Label
        l = Label('Heritage types', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.session.flush()
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

class CollectionTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Collection
        return Collection

    def _get_concept(self):
        from ..models import Concept, Label
        return Concept(
            id=2,
            labels=[Label('Cathedrals', 'prefLabel', 'en')]
        )

    def test_simple(self):
        from ..models import Label
        l = Label('Churches by function', 'prefLabel', 'en')
        c = self._get_target_class()(
            id=1,
            labels=[l]
        )
        self.assertEqual(1, c.id)
        self.assertEqual(l, c.label())

    def test_members(self):
        col = self._get_target_class()(
            id=1
        )
        c = self._get_concept()
        col.members.append(c)
        self.session.flush()
        self.assertEqual(1, len(c.collections))
        self.assertEqual(col, c.collections[0])

class LabelTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Label
        return Label

    def test_simple(self):
        l = self._get_target_class()('Kerken', 'prefLabel', 'nl')
        self.assertEqual('nl', l.language_id)
        self.assertEqual('prefLabel', l.labeltype_id)
        self.assertEqual('Kerken', l.__str__())

    def test_load_objects(self):
        l = self._get_target_class()('Kerken', 'prefLabel', 'nl')
        self.session.add(l)
        self.session.flush()
        self.assertEqual('Dutch', l.language.name)
        self.assertEqual('prefLabel', l.labeltype.name)

    def test_no_language(self):
        l = self._get_target_class()('Kerken', 'prefLabel')
        self.assertEqual(None, l.language_id)
        self.assertEqual('prefLabel', l.labeltype_id)
        self.assertEqual('Kerken', l.__str__())
        self.session.add(l)
        self.session.flush()
        self.assertEqual(None, l.language_id)
        self.assertEqual('prefLabel', l.labeltype.name)

class NoteTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Note
        return Note

    def test_simple(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            'nl'
        )
        self.assertEqual('nl', n.language_id)
        self.assertEqual('definition', n.notetype_id)
        self.assertEqual('Een kerk is een religieus gebouw.', n.__str__())

    def test_load_objects(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            'nl'
        )
        self.session.add(n)
        self.session.flush()
        self.assertEqual('Dutch', n.language.name)
        self.assertEqual('definition', n.notetype.name)

    def test_no_language(self):
        n = self._get_target_class()(
            'Een kerk is een religieus gebouw.',
            'definition',
            None
        )
        self.assertEqual(None, n.language_id)
        self.assertEqual('definition', n.notetype_id)
        self.assertEqual('Een kerk is een religieus gebouw.', n.__str__())
        self.session.add(n)
        self.session.flush()
        self.assertEqual(None, n.language)
        self.assertEqual('definition', n.notetype.name)

class LanguageTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import Language
        return Language

    def test_simple(self):
        l = self._get_target_class()('nl', 'Dutch')
        self.assertEqual('nl', l.id)
        self.assertEqual('Dutch', l.name)
        self.assertEqual('Dutch', l.__str__())

class LabelTypeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import LabelType
        return LabelType

    def test_simple(self):
        l = self._get_target_class()('prefLabel', 'Preferred label')
        self.assertEqual('prefLabel', l.name)
        self.assertEqual('Preferred label', l.description)
        self.assertEqual('prefLabel', l.__str__())

class NoteTypeTests(ModelTestCase):

    def _get_target_class(self):
        from ..models import NoteType
        return NoteType

    def test_simple(self):
        n = self._get_target_class()('definition', 'A definition.')
        self.assertEqual('definition', n.name)
        self.assertEqual('A definition.', n.description)
        self.assertEqual('definition', n.__str__())

class LabelFunctionTest(ModelTestCase):

    def _get_fut(self):
        from ..models import label
        return label

    def _get_knokke_heist_nl(self):
        from ..models import Label
        return Label('Knokke-Heist', "prefLabel", 'nl')

    def _get_cnocke_heyst_nl(self):
        from ..models import Label
        return Label('Cnock-Heyst', "altLabel", 'nl')

    def _get_knokke_heist_en(self):
        from ..models import Label
        return Label('Knocke-Heyst', "prefLabel", 'en')

    def test_label_empty(self):
        label = self._get_fut()
        self.assertEqual(None, label([]))
        self.assertEqual(None, label([], 'nl'))
        self.assertEqual(None, label([], None))

    def test_label_pref(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        labels = [kh]
        self.assertEqual(kh, label(labels))
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(kh, label(labels, 'en'))
        self.assertEqual(kh, label(labels, None))

    def test_label_pref_nl_and_en(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        khen = self._get_knokke_heist_en()
        labels = [kh, khen]
        self.assertIn(label(labels), [kh, khen])
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(khen, label(labels, 'en'))
        self.assertIn(label(labels, None), [kh, khen])

    def test_label_alt(self):
        label = self._get_fut()
        ch = self._get_cnocke_heyst_nl()
        labels = [ch]
        self.assertEqual(ch, label(labels))
        self.assertEqual(ch, label(labels, 'nl'))
        self.assertEqual(ch, label(labels, 'en'))
        self.assertEqual(ch, label(labels, None))

    def test_pref_precedes_alt(self):
        label = self._get_fut()
        kh = self._get_knokke_heist_nl()
        ch = self._get_cnocke_heyst_nl()
        labels = [kh, ch]
        self.assertEqual(kh, label(labels))
        self.assertEqual(kh, label(labels, 'nl'))
        self.assertEqual(kh, label(labels, 'en'))
        self.assertEqual(kh, label(labels, None))
<|endoftext|>


<commit_before>import pytest
from ftw import testrunner, errors

def test_default(ruleset, test, destaddr):
    """
    Default tester with no logger obj. Useful for HTML contains and Status code
    Not useful for testing loggers
    """
    runner = testrunner.TestRunner()
    try:
        for stage in test.stages:
            if destaddr is not None:
                stage.input.dest_addr = destaddr
            runner.run_stage(stage, None)
    except errors.TestError as e:
        e.args[1]['meta'] = ruleset.meta
        pytest.fail('Failure! Message -> {0}, Context -> {1}'
<commit_msg>test default added<commit_after>import pytest
from ftw import testrunner, errors

def test_default(ruleset, test, destaddr):
    """
    Default tester with no logger obj. Useful for HTML contains and Status code
    Not useful for testing loggers
    """
    runner = testrunner.TestRunner()
    try:
        for stage in test.stages:
            if destaddr is not None:
                stage.input.dest_addr = destaddr
            runner.run_stage(stage, None)
    except errors.TestError as e:
        e.args[1]['meta'] = ruleset.meta
        pytest.fail('Failure! Message -> {0}, Context -> {1}'
                        .format(e.args[0],e.args[1]))
<|endoftext|>


<commit_before>from ev3.ev3dev import Key
import unittest
from util import get_input
import time

class TestTone(unittest.TestCase):

    def test_tone(self):
        d = Key()
        get_input('Test keyboard. Hold Up key')
        print(d.up)
        get_input('Test keyboard. Release Up key')
        print(d.up)
        get_input('Test keyboard. Hold Down key')
        print(d.down)
        get_input('Test keyboard. Release Down key')
        print(d.down)
        get_input('Test keyboard. Hold Left key')
        print(d.left)
        get_input('Test keyboard. Release Left key')
        print(d.left)
        get_input('Test keyboard. Hold Right key')
        print(d.right)
        get_input('Test keyboard. Release Right key')
        print(d.right)
        get_input('Test keyboard. Hold Backspace key')
        print(d.backspace)
        get_input('Test keyboard. Release Backspace key')
        print(d.backspace)
        get_input('Test keyboard. Hold Enter key')
        print(d.enter)
        get_input('Test keyboard. Release Enter key')
        print(d.enter)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Change dname of key test<commit_after>from ev3.ev3dev import Key
import unittest
from util import get_input

class TestKey(unittest.TestCase):

    def test_key(self):
        d = Key()
        get_input('Test keyboard. Hold Up key')
        print(d.up)
        get_input('Test keyboard. Release Up key')
        print(d.up)
        get_input('Test keyboard. Hold Down key')
        print(d.down)
        get_input('Test keyboard. Release Down key')
        print(d.down)
        get_input('Test keyboard. Hold Left key')
        print(d.left)
        get_input('Test keyboard. Release Left key')
        print(d.left)
        get_input('Test keyboard. Hold Right key')
        print(d.right)
        get_input('Test keyboard. Release Right key')
        print(d.right)
        get_input('Test keyboard. Hold Backspace key')
        print(d.backspace)
        get_input('Test keyboard. Release Backspace key')
        print(d.backspace)
        get_input('Test keyboard. Hold Enter key')
        print(d.enter)
        get_input('Test keyboard. Release Enter key')
        print(d.enter)

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


<commit_before>""" Test suite for the interactive module.

The script can be executed on its own or incorporated into a larger test suite.
However the tests are run, be aware of which version of the module is actually
being tested. If the library is installed in site-packages, that version takes
precedence over the version in this project directory. Use a virtualenv test
environment or setuptools develop mode to test against the development version.

"""
import datetime
import pytest
from mock import Mock

from githeat.githeat import Githeat, Commit
from static.test_logs import test_logs

@pytest.fixture
def test_repo():

    def log(arguments):
        return test_logs

    repo = Mock(log=log)
    githeat = Githeat(repo)
    githeat.parse_commits()
    githeat.init_daily_contribution_map()
    githeat.compute_daily_contribution_map()
    githeat.normalize_daily_contribution_map()

    return githeat

def test_githeat_init(test_repo):
    assert len(test_repo.commits_db) == 367

def test_toggle_day_(test_repo):
    test_repo.toggle_day(0)
    assert test_repo.days == ["Sunday"]
    test_repo.toggle_day(0)
    assert test_repo.days == []
    test_repo.toggle_day(0)
    test_repo.toggle_day(1)
    test_repo.toggle_day(2)
    test_repo.toggle_day(3)
    test_repo.toggle_day(4)
    test_repo.toggle_day(5)
    test_repo.toggle_day(6)
    assert test_repo.days == ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
                              'Friday', 'Saturday']

def test_toggle_day_invalid_day_num(test_repo):
    test_repo.toggle_day(-1)
    assert test_repo.days == []

def test_toggle_month(test_repo):
    test_repo.toggle_month(0)
    assert test_repo.display_months == [datetime.date(2015, 6, 1)]
    test_repo.toggle_month(0)
    assert test_repo.display_months == []

def test_reset_daily_contribution_map(test_repo):
    test_repo.reset_daily_contribution_map()
    for d in test_repo.daily_contribution_map:
        assert test_repo.daily_contribution_map[d] == 0.0

def test_compute_daily_contribution_map_specific_days(test_repo):
    test_repo.days = ["Sunday"]
    test_repo.reset_daily_contribution_map()
    test_repo.compute_daily_contribution_map()
    for d in test_repo.daily_contribution_map:
        if test_repo.daily_contribution_map[d] != 0.0:
            assert d.strftime("%A") == "Sunday"

def test_normalize_daily_contribution_map(test_repo):
    for d in test_repo.daily_contribution_map:
        assert 0 <= test_repo.daily_contribution_map[d] <= 5

def test_compute_graph_matrix(test_repo):
    matrix = test_repo.compute_graph_matrix()
    assert matrix[0].col[0][0].strftime("%A") == "Sunday"
    test_repo.month_merge = True
    test_repo.width = " "  # thin block
    assert test_repo.get_matrix_width(matrix) == 53
    test_repo.width = "   "  # thick block
    assert test_repo.get_matrix_width(matrix) == 159
    test_repo.width = "  "  # reg block
    assert test_repo.get_matrix_width(matrix) == 106

def test_get_top_n_commiters(test_repo):
    assert test_repo.get_top_n_commiters([]) is None
    authors_list = [Commit(None, None, "James", None, None)] * 3 + \
                   [Commit(None, None, "John", None, None),
                    Commit(None, None, "JJ", None, None)]
    assert test_repo.get_top_n_commiters(authors_list) == [('James', 3),
                                                           ('John', 1),
                                                           ('JJ', 1)]

    authors_list = [Commit(None, None, "James", None, None)] * 30 + \
                   [Commit(None, None, "John", None, None)] * 10 + \
                   [Commit(None, None, "JJ", None, None)] * 5
    assert test_repo.get_top_n_commiters(authors_list,
                                         normailze_values=True) == [('James', 5),
                                                                    ('John', 2),
                                                                    ('JJ', 1)]

# Make the script executable.
if __name__ == "__main__":
    raise SystemExit(pytest.main(__file__))
<commit_msg>Update month toggling test case<commit_after>""" Test suite for the interactive module.

The script can be executed on its own or incorporated into a larger test suite.
However the tests are run, be aware of which version of the module is actually
being tested. If the library is installed in site-packages, that version takes
precedence over the version in this project directory. Use a virtualenv test
environment or setuptools develop mode to test against the development version.

"""
import datetime
import pytest
from mock import Mock

from githeat.githeat import Githeat, Commit
from static.test_logs import test_logs

@pytest.fixture
def test_repo():

    def log(arguments):
        return test_logs

    repo = Mock(log=log)
    githeat = Githeat(repo)
    githeat.parse_commits()
    githeat.init_daily_contribution_map()
    githeat.compute_daily_contribution_map()
    githeat.normalize_daily_contribution_map()

    return githeat

def test_githeat_init(test_repo):
    assert len(test_repo.commits_db) == 367

def test_toggle_day_(test_repo):
    test_repo.toggle_day(0)
    assert test_repo.days == ["Sunday"]
    test_repo.toggle_day(0)
    assert test_repo.days == []
    test_repo.toggle_day(0)
    test_repo.toggle_day(1)
    test_repo.toggle_day(2)
    test_repo.toggle_day(3)
    test_repo.toggle_day(4)
    test_repo.toggle_day(5)
    test_repo.toggle_day(6)
    assert test_repo.days == ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
                              'Friday', 'Saturday']

def test_toggle_day_invalid_day_num(test_repo):
    test_repo.toggle_day(-1)
    assert test_repo.days == []

def test_toggle_month(test_repo):
    test_repo.toggle_month(0)
    today = datetime.datetime.now()
    last_year = datetime.date(today.year - 1, today.month, 1)
    assert test_repo.display_months == [last_year]
    test_repo.toggle_month(0)
    assert test_repo.display_months == []

def test_reset_daily_contribution_map(test_repo):
    test_repo.reset_daily_contribution_map()
    for d in test_repo.daily_contribution_map:
        assert test_repo.daily_contribution_map[d] == 0.0

def test_compute_daily_contribution_map_specific_days(test_repo):
    test_repo.days = ["Sunday"]
    test_repo.reset_daily_contribution_map()
    test_repo.compute_daily_contribution_map()
    for d in test_repo.daily_contribution_map:
        if test_repo.daily_contribution_map[d] != 0.0:
            assert d.strftime("%A") == "Sunday"

def test_normalize_daily_contribution_map(test_repo):
    for d in test_repo.daily_contribution_map:
        assert 0 <= test_repo.daily_contribution_map[d] <= 5

def test_compute_graph_matrix(test_repo):
    matrix = test_repo.compute_graph_matrix()
    assert matrix[0].col[0][0].strftime("%A") == "Sunday"
    test_repo.month_merge = True
    test_repo.width = " "  # thin block
    assert test_repo.get_matrix_width(matrix) == 53
    test_repo.width = "   "  # thick block
    assert test_repo.get_matrix_width(matrix) == 159
    test_repo.width = "  "  # reg block
    assert test_repo.get_matrix_width(matrix) == 106

def test_get_top_n_commiters(test_repo):
    assert test_repo.get_top_n_commiters([]) is None
    authors_list = [Commit(None, None, "James", None, None)] * 3 + \
                   [Commit(None, None, "John", None, None),
                    Commit(None, None, "JJ", None, None)]
    assert test_repo.get_top_n_commiters(authors_list) == [('James', 3),
                                                           ('John', 1),
                                                           ('JJ', 1)]

    authors_list = [Commit(None, None, "James", None, None)] * 30 + \
                   [Commit(None, None, "John", None, None)] * 10 + \
                   [Commit(None, None, "JJ", None, None)] * 5
    assert test_repo.get_top_n_commiters(authors_list,
                                         normailze_values=True) == [('James', 5),
                                                                    ('John', 2),
                                                                    ('JJ', 1)]

# Make the script executable.
if __name__ == "__main__":
    raise SystemExit(pytest.main(__file__))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import os
import unittest
import gittool

test_dir_root = os.path.dirname(os.path.realpath(__file__))

class MethodsReturnType(unittest.TestCase):
    """
    Tests output types of the methods.
    """
    def test_list_tl_subdirs(self):
        """
        list_tl_subdirs should return a list.
        """
        self.assertIsInstance(gittool.list_tl_subdirs(test_dir_root), list)

    def test_list_empty_subdirs(self):
        """
        list_empty_subdirs should return a list.
        """
        self.assertIsInstance(gittool.list_empty_subdirs(test_dir_root), list)

class MethodsReturnValues(unittest.TestCase):
    """
    Tests output values of the methods where applicable.
    """
    pass
<commit_msg>Comment.<commit_after># -*- coding: utf-8 -*-
import os
import unittest
import gittool

# Variable containing the fully qualified path name of the directory containing these tests.
test_dir_root = os.path.dirname(os.path.realpath(__file__))

class MethodsReturnType(unittest.TestCase):
    """
    Tests output types of the methods.
    """
    def test_list_tl_subdirs(self):
        """
        list_tl_subdirs should return a list.
        """
        self.assertIsInstance(gittool.list_tl_subdirs(test_dir_root), list)

    def test_list_empty_subdirs(self):
        """
        list_empty_subdirs should return a list.
        """
        self.assertIsInstance(gittool.list_empty_subdirs(test_dir_root), list)

class MethodsReturnValues(unittest.TestCase):
    """
    Tests output values of the methods where applicable.
    """
    pass
<|endoftext|>


<commit_before>#!/usr/bin/python -t
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Copyright 2002-2003 Michael D. Stenner, Ryan D. Tomayko

import sys
sys.path.insert(0, '.')

import unittest

from unittest import TestCase, TestSuite

import grabber
from grabber import URLGrabber, urlgrab, urlopen, urlread
from progress import text_progress_meter

def suite():
    return TestSuite((
        unittest.makeSuite(FileObjectTests,'test'),
        unittest.makeSuite(HTTPTests,'test'),
        unittest.makeSuite(URLGrabberModuleTestCase,'test'),
        unittest.makeSuite(URLGrabberTestCase,'test')
        ))

import string, tempfile, random, cStringIO, os

reference_data = ''.join( [str(i)+'\n' for i in range(20000) ] )

class FileObjectTests(unittest.TestCase):
    def setUp(self):
        self.filename = tempfile.mktemp()
        fo = open(self.filename, 'w')
        fo.write(reference_data)
        fo.close()

        self.fo_input = cStringIO.StringIO(reference_data)
        self.fo_output = cStringIO.StringIO()
        self.wrapper = grabber.URLGrabberFileObject('file://' + self.filename, self.fo_output,
                             grabber.default_grabber.opts)

    def tearDown(self):
        os.unlink(self.filename)

    def test_readall(self):
        s = self.wrapper.read()
        self.fo_output.write(s)
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_readline(self):
        while 1:
            s = self.wrapper.readline()
            self.fo_output.write(s)
            if not s: break
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_readlines(self):
        li = self.wrapper.readlines()
        self.fo_output.write(string.join(li, ''))
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_smallread(self):
        while 1:
            s = self.wrapper.read(23)
            self.fo_output.write(s)
            if not s: break
        self.assertEqual(reference_data, self.fo_output.getvalue())

class HTTPTests(unittest.TestCase):
    base_url = 'http://www.linux.duke.edu/projects/mini/urlgrabber/test/'
    def test_reference_file(self):
        """test that a reference file can be properly downloaded via http"""
        filename = tempfile.mktemp()
        url = self.base_url + 'reference'
        grabber.urlgrab(url, filename)

        fo = open(filename)
        contents = fo.read()
        fo.close()

        self.assertEqual(contents, reference_data)

class URLGrabberModuleTestCase(TestCase):
    """Test module level functions defined in grabber.py"""
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_urlopen(self):
        """grabber.urlopen()"""
        fo = grabber.urlopen('http://www.python.org')
        fo.close()

    def test_urlgrab(self):
        """grabber.urlgrab()"""
        filename = grabber.urlgrab('http://www.python.org',
                                    filename='www.python.org')

    def test_urlread(self):
        """grabber.urlread()"""
        s = grabber.urlread('http://www.python.org')

class URLGrabberTestCase(TestCase):
    """Test grabber.URLGrabber class"""

    def setUp(self):
        self.meter = text_progress_meter( fo=open('/dev/null', 'w') )
        pass

    def tearDown(self):
        pass

    def testKeywordArgs(self):
        """grabber.URLGrabber.__init__() **kwargs handling.

        This is a simple test that just passes some arbitrary
        values into the URLGrabber constructor and checks that
        they've been set properly.
        """
        g = URLGrabber( progress_obj=self.meter,
                        throttle=0.9,
                        bandwidth=20,
                        retry=20,
                        retrycodes=[5,6,7],
                        copy_local=1,
                        close_connection=1,
                        user_agent='test ua/1.0',
                        proxies={'http' : 'http://www.proxy.com:9090'} )
        opts = g.opts
        self.assertEquals( opts.progress_obj, self.meter )
        self.assertEquals( opts.throttle, 0.9 )
        self.assertEquals( opts.bandwidth, 20 )
        self.assertEquals( opts.retry, 20 )
        self.assertEquals( opts.retrycodes, [5,6,7] )
        self.assertEquals( opts.copy_local, 1 )
        self.assertEquals( opts.close_connection, 1 )
        self.assertEquals( opts.user_agent, 'test ua/1.0' )
        self.assertEquals( opts.proxies, {'http' : 'http://www.proxy.com:9090'} )

    def test_parse_url(self):
        """grabber.URLGrabber._parse_url()"""
        g = URLGrabber()
        (url, parts) = g._parse_url('http://user:pass@host.com/path/part/basename.ext?arg1=val1&arg2=val2#hash')
        (scheme, host, path, parm, query, frag) = parts
        self.assertEquals('http://host.com/path/part/basename.ext?arg1=val1&arg2=val2#hash',url)
        self.assertEquals('http', scheme)
        self.assertEquals('host.com', host)
        self.assertEquals('/path/part/basename.ext', path)
        self.assertEquals('arg1=val1&arg2=val2', query)
        self.assertEquals('hash', frag)

    def test_parse_url_local_filename(self):
        """grabber.URLGrabber._parse_url('/local/file/path') """
        g = URLGrabber()
        (url, parts) = g._parse_url('/etc/redhat-release')
        (scheme, host, path, parm, query, frag) = parts
        self.assertEquals('file:///etc/redhat-release',url)
        self.assertEquals('file', scheme)
        self.assertEquals('', host)
        self.assertEquals('/etc/redhat-release', path)
        self.assertEquals('', query)
        self.assertEquals('', frag)

# I'd like to write some ftp tests as well, but I don't have a
# reliable ftp server

if __name__ == '__main__':
    grabber.DEBUG = 1
    runner = unittest.TextTestRunner(descriptions=1,verbosity=2)
    runner.run(suite())

<commit_msg>Clean up temp files after testing urlgrab.<commit_after>#!/usr/bin/python -t
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Copyright 2002-2003 Michael D. Stenner, Ryan D. Tomayko

import sys
sys.path.insert(0, '.')

import unittest
import os

from unittest import TestCase, TestSuite

import grabber
from grabber import URLGrabber, urlgrab, urlopen, urlread
from progress import text_progress_meter

def suite():
    return TestSuite((
        unittest.makeSuite(FileObjectTests,'test'),
        unittest.makeSuite(HTTPTests,'test'),
        unittest.makeSuite(URLGrabberModuleTestCase,'test'),
        unittest.makeSuite(URLGrabberTestCase,'test')
        ))

import string, tempfile, random, cStringIO, os

reference_data = ''.join( [str(i)+'\n' for i in range(20000) ] )

class FileObjectTests(unittest.TestCase):
    def setUp(self):
        self.filename = tempfile.mktemp()
        fo = open(self.filename, 'w')
        fo.write(reference_data)
        fo.close()

        self.fo_input = cStringIO.StringIO(reference_data)
        self.fo_output = cStringIO.StringIO()
        self.wrapper = grabber.URLGrabberFileObject('file://' + self.filename, self.fo_output,
                             grabber.default_grabber.opts)

    def tearDown(self):
        os.unlink(self.filename)

    def test_readall(self):
        s = self.wrapper.read()
        self.fo_output.write(s)
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_readline(self):
        while 1:
            s = self.wrapper.readline()
            self.fo_output.write(s)
            if not s: break
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_readlines(self):
        li = self.wrapper.readlines()
        self.fo_output.write(string.join(li, ''))
        self.assertEqual(reference_data, self.fo_output.getvalue())

    def test_smallread(self):
        while 1:
            s = self.wrapper.read(23)
            self.fo_output.write(s)
            if not s: break
        self.assertEqual(reference_data, self.fo_output.getvalue())

class HTTPTests(unittest.TestCase):
    base_url = 'http://www.linux.duke.edu/projects/mini/urlgrabber/test/'
    def test_reference_file(self):
        """test that a reference file can be properly downloaded via http"""
        filename = tempfile.mktemp()
        url = self.base_url + 'reference'
        grabber.urlgrab(url, filename)

        fo = open(filename)
        contents = fo.read()
        fo.close()

        self.assertEqual(contents, reference_data)

class URLGrabberModuleTestCase(TestCase):
    """Test module level functions defined in grabber.py"""
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_urlopen(self):
        """grabber.urlopen()"""
        fo = grabber.urlopen('http://www.python.org')
        fo.close()

    def test_urlgrab(self):
        """grabber.urlgrab()"""
        filename = grabber.urlgrab('http://www.python.org',
                                    filename='www.python.org')
        os.unlink('www.python.org')

    def test_urlread(self):
        """grabber.urlread()"""
        s = grabber.urlread('http://www.python.org')

class URLGrabberTestCase(TestCase):
    """Test grabber.URLGrabber class"""

    def setUp(self):
        self.meter = text_progress_meter( fo=open('/dev/null', 'w') )
        pass

    def tearDown(self):
        pass

    def testKeywordArgs(self):
        """grabber.URLGrabber.__init__() **kwargs handling.

        This is a simple test that just passes some arbitrary
        values into the URLGrabber constructor and checks that
        they've been set properly.
        """
        g = URLGrabber( progress_obj=self.meter,
                        throttle=0.9,
                        bandwidth=20,
                        retry=20,
                        retrycodes=[5,6,7],
                        copy_local=1,
                        close_connection=1,
                        user_agent='test ua/1.0',
                        proxies={'http' : 'http://www.proxy.com:9090'} )
        opts = g.opts
        self.assertEquals( opts.progress_obj, self.meter )
        self.assertEquals( opts.throttle, 0.9 )
        self.assertEquals( opts.bandwidth, 20 )
        self.assertEquals( opts.retry, 20 )
        self.assertEquals( opts.retrycodes, [5,6,7] )
        self.assertEquals( opts.copy_local, 1 )
        self.assertEquals( opts.close_connection, 1 )
        self.assertEquals( opts.user_agent, 'test ua/1.0' )
        self.assertEquals( opts.proxies, {'http' : 'http://www.proxy.com:9090'} )

    def test_parse_url(self):
        """grabber.URLGrabber._parse_url()"""
        g = URLGrabber()
        (url, parts) = g._parse_url('http://user:pass@host.com/path/part/basename.ext?arg1=val1&arg2=val2#hash')
        (scheme, host, path, parm, query, frag) = parts
        self.assertEquals('http://host.com/path/part/basename.ext?arg1=val1&arg2=val2#hash',url)
        self.assertEquals('http', scheme)
        self.assertEquals('host.com', host)
        self.assertEquals('/path/part/basename.ext', path)
        self.assertEquals('arg1=val1&arg2=val2', query)
        self.assertEquals('hash', frag)

    def test_parse_url_local_filename(self):
        """grabber.URLGrabber._parse_url('/local/file/path') """
        g = URLGrabber()
        (url, parts) = g._parse_url('/etc/redhat-release')
        (scheme, host, path, parm, query, frag) = parts
        self.assertEquals('file:///etc/redhat-release',url)
        self.assertEquals('file', scheme)
        self.assertEquals('', host)
        self.assertEquals('/etc/redhat-release', path)
        self.assertEquals('', query)
        self.assertEquals('', frag)

# I'd like to write some ftp tests as well, but I don't have a
# reliable ftp server

if __name__ == '__main__':
    grabber.DEBUG = 1
    runner = unittest.TextTestRunner(descriptions=1,verbosity=2)
    runner.run(suite())

<|endoftext|>


<commit_before># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# 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 base import Fixtures
from helper import web as web_helper
from pybossa.hateoas import Hateoas

class TestHateoas(web_helper.Helper):
    url = "/app/%s/tasks/export" % Fixtures.app_short_name

    hateoas = Hateoas()

    def setUp(self):
        super(TestHateoas, self).setUp()
        Fixtures.create()

    # Tests

    def test_00_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        # For task
        res = self.app.get("/api/task/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

        # For category
        res = self.app.get("/api/category/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        category_link = self.hateoas.link(rel='self', title='category',
                                          href='http://localhost/api/category/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert category_link == output['link'], err_msg
        err_msg = "There should be no other links"
        assert output.get('links') is None, err_msg
        err_msg = "The object links should are wrong"

        # For user
        # Pending define what user fields will be visible through the API
        # Issue #626. For now let's suppose link and links are not visible
        # res = self.app.get("/api/user/1?api_key=" + Fixtures.root_api_key, follow_redirects=True)
        # output = json.loads(res.data)
        # err_msg = "There should be a Link with the object URI"
        # assert output['link'] is not None, err_msg
        # user_link = self.hateoas.link(rel='self', title='user',
        #                               href='http://localhost/api/user/1')
        # err_msg = "The object link ir wrong: %s" % output['link']
        # assert user_link == output['link'], err_msg
        # # when the links specification of a user will be set, modify the following
        # err_msg = "The list of links should be empty for now"
        # assert output.get('links') == None, err_msg

    def test_01_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')

        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        # For task
        res = self.app.get("/api/task", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

        # For category
        res = self.app.get("/api/category", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        category_link = self.hateoas.link(rel='self', title='category',
                                      href='http://localhost/api/category/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert category_link == output['link'], err_msg
        err_msg = "There should be no other links"
        assert output.get('links') is None, err_msg
        err_msg = "The object links should are wrong"

        # For user
        # Pending define what user fields will be visible through the API
        # Issue #626. For now let's suppose link and links are not visible
        # res = self.app.get("/api/user?api_key=" + Fixtures.root_api_key, follow_redirects=True)
        # output = json.loads(res.data)[0]
        # err_msg = "There should be a Link with the object URI"
        # assert output['link'] is not None, err_msg
        # user_link = self.hateoas.link(rel='self', title='user',
        #                               href='http://localhost/api/user/1')
        # err_msg = "The object link ir wrong: %s" % output['link']
        # assert user_link == output['link'], err_msg
        # # when the links specification of a user will be set, modify the following
        # err_msg = "The list of links should be empty for now"
        # assert output.get('links') == None, err_msg
<commit_msg>Removed non-used url variable from test_hateoas.py, referencing task exports<commit_after># -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# 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 base import Fixtures
from helper import web as web_helper
from pybossa.hateoas import Hateoas

class TestHateoas(web_helper.Helper):

    hateoas = Hateoas()

    def setUp(self):
        super(TestHateoas, self).setUp()
        Fixtures.create()

    # Tests

    def test_00_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        # For task
        res = self.app.get("/api/task/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

        # For category
        res = self.app.get("/api/category/1", follow_redirects=True)
        output = json.loads(res.data)
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        category_link = self.hateoas.link(rel='self', title='category',
                                          href='http://localhost/api/category/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert category_link == output['link'], err_msg
        err_msg = "There should be no other links"
        assert output.get('links') is None, err_msg
        err_msg = "The object links should are wrong"

        # For user
        # Pending define what user fields will be visible through the API
        # Issue #626. For now let's suppose link and links are not visible
        # res = self.app.get("/api/user/1?api_key=" + Fixtures.root_api_key, follow_redirects=True)
        # output = json.loads(res.data)
        # err_msg = "There should be a Link with the object URI"
        # assert output['link'] is not None, err_msg
        # user_link = self.hateoas.link(rel='self', title='user',
        #                               href='http://localhost/api/user/1')
        # err_msg = "The object link ir wrong: %s" % output['link']
        # assert user_link == output['link'], err_msg
        # # when the links specification of a user will be set, modify the following
        # err_msg = "The list of links should be empty for now"
        # assert output.get('links') == None, err_msg

    def test_01_link_object(self):
        """Test HATEOAS object link is created"""
        # For app
        res = self.app.get("/api/app", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        app_link = self.hateoas.link(rel='self', title='app',
                                     href='http://localhost/api/app/1')

        err_msg = "The object link is wrong: %s" % output['link']
        assert app_link == output['link'], err_msg

        err_msg = "There should be a Links list with the category URI"
        assert output['links'] is not None, err_msg
        assert len(output['links']) == 1, err_msg
        app_link = self.hateoas.link(rel='category', title='category',
                                     href='http://localhost/api/category/1')
        assert app_link == output['links'][0], err_msg

        # For task
        res = self.app.get("/api/task", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='task',
                                      href='http://localhost/api/task/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be one parent link: app"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 1, err_msg
        err_msg = "The parent link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        # For taskrun
        res = self.app.get("/api/taskrun", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        task_link = self.hateoas.link(rel='self', title='taskrun',
                                      href='http://localhost/api/taskrun/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert task_link == output['link'], err_msg
        err_msg = "There should be two parent links: app and task"
        assert output.get('links') is not None, err_msg
        assert len(output.get('links')) == 2, err_msg
        err_msg = "The parent app link is wrong"
        app_link = self.hateoas.link(rel='parent', title='app',
                                     href='http://localhost/api/app/1')
        assert output.get('links')[0] == app_link, err_msg

        err_msg = "The parent task link is wrong"
        app_link = self.hateoas.link(rel='parent', title='task',
                                     href='http://localhost/api/task/1')
        assert output.get('links')[1] == app_link, err_msg

        # For category
        res = self.app.get("/api/category", follow_redirects=True)
        output = json.loads(res.data)[0]
        err_msg = "There should be a Link with the object URI"
        assert output['link'] is not None, err_msg
        category_link = self.hateoas.link(rel='self', title='category',
                                      href='http://localhost/api/category/1')
        err_msg = "The object link is wrong: %s" % output['link']
        assert category_link == output['link'], err_msg
        err_msg = "There should be no other links"
        assert output.get('links') is None, err_msg
        err_msg = "The object links should are wrong"

        # For user
        # Pending define what user fields will be visible through the API
        # Issue #626. For now let's suppose link and links are not visible
        # res = self.app.get("/api/user?api_key=" + Fixtures.root_api_key, follow_redirects=True)
        # output = json.loads(res.data)[0]
        # err_msg = "There should be a Link with the object URI"
        # assert output['link'] is not None, err_msg
        # user_link = self.hateoas.link(rel='self', title='user',
        #                               href='http://localhost/api/user/1')
        # err_msg = "The object link ir wrong: %s" % output['link']
        # assert user_link == output['link'], err_msg
        # # when the links specification of a user will be set, modify the following
        # err_msg = "The list of links should be empty for now"
        # assert output.get('links') == None, err_msg
<|endoftext|>


<commit_before>"""Tests for ClientCookie._HeadersUtil."""

from unittest import TestCase

class IsHtmlTests(TestCase):
    def test_is_html(self):
        from mechanize._headersutil import is_html
        for allow_xhtml in False, True:
            for cths, ext, expect in [
                (["text/html"], ".html", True),
                (["text/html", "text/plain"], ".html", True),
                # Content-type takes priority over file extension from URL
                (["text/html"], ".txt", True),
                (["text/plain"], ".html", False),
                # use extension if no Content-Type
                ([], ".html", True),
                ([], ".gif", False),
                # don't regard XHTML as HTML (unless user explicitly asks for it),
                # since we don't yet handle XML properly
                ([], ".xhtml", allow_xhtml),
                (["text/xhtml"], ".xhtml", allow_xhtml),
                ]:
                url = "http://example.com/foo"+ext
                self.assertEqual(expect, is_html(cths, url, allow_xhtml))

class HeaderTests(TestCase):
    def test_parse_ns_headers_expires(self):
        from mechanize._headersutil import parse_ns_headers

        # quotes should be stripped
        assert parse_ns_headers(['foo=bar; expires=01 Jan 2040 22:23:32 GMT']) == \
               [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]]
        assert parse_ns_headers(['foo=bar; expires="01 Jan 2040 22:23:32 GMT"']) == \
               [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]]

    def test_parse_ns_headers_version(self):
        from mechanize._headersutil import parse_ns_headers

        # quotes should be stripped
        expected = [[('foo', 'bar'), ('version', '1')]]
        for hdr in [
            'foo=bar; version="1"',
            'foo=bar; Version="1"',
            ]:
            self.assertEquals(parse_ns_headers([hdr]), expected)

    def test_parse_ns_headers_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from mechanize._headersutil import parse_ns_headers

        # Cookie with name 'expires'
        hdr = 'expires=01 Jan 2040 22:23:32 GMT'
        expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
        self.assertEquals(parse_ns_headers([hdr]), expected)

    def test_join_header_words(self):
        from mechanize._headersutil import join_header_words

        assert join_header_words([[
            ("foo", None), ("bar", "baz"), (None, "value")
            ]]) == "foo; bar=baz; value"

        assert join_header_words([[]]) == ""

    def test_split_header_words(self):
        from mechanize._headersutil import split_header_words

        tests = [
            ("foo", [[("foo", None)]]),
            ("foo=bar", [[("foo", "bar")]]),
            ("   foo   ", [[("foo", None)]]),
            ("   foo=   ", [[("foo", "")]]),
            ("   foo=", [[("foo", "")]]),
            ("   foo=   ; ", [[("foo", "")]]),
            ("   foo=   ; bar= baz ", [[("foo", ""), ("bar", "baz")]]),
            ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
            # doesn't really matter if this next fails, but it works ATM
            ("foo= bar=baz", [[("foo", "bar=baz")]]),
            ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
            ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]),
            ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]),
            (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ',
             [[("foo", None), ("bar", "baz")],
              [("spam", "")], [("foo", ',;"')], [("bar", "")]]),
            ]

        for arg, expect in tests:
            try:
                result = split_header_words([arg])
            except:
                import traceback, StringIO
                f = StringIO.StringIO()
                traceback.print_exc(None, f)
                result = "(error -- traceback follows)\n\n%s" % f.getvalue()
            assert result == expect, """
When parsing: '%s'
Expected:     '%s'
Got:          '%s'
""" % (arg, expect, result)

    def test_roundtrip(self):
        from mechanize._headersutil import split_header_words, join_header_words

        tests = [
            ("foo", "foo"),
            ("foo=bar", "foo=bar"),
            ("   foo   ", "foo"),
            ("foo=", 'foo=""'),
            ("foo=bar bar=baz", "foo=bar; bar=baz"),
            ("foo=bar;bar=baz", "foo=bar; bar=baz"),
            ('foo bar baz', "foo; bar; baz"),
            (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'),
            ('foo,,,bar', 'foo, bar'),
            ('foo=bar,bar=baz', 'foo=bar, bar=baz'),

            ('text/html; charset=iso-8859-1',
             'text/html; charset="iso-8859-1"'),

            ('foo="bar"; port="80,81"; discard, bar=baz',
             'foo=bar; port="80,81"; discard, bar=baz'),

            (r'Basic realm="\"foo\\\\bar\""',
             r'Basic; realm="\"foo\\\\bar\""')
            ]

        for arg, expect in tests:
            input = split_header_words([arg])
            res = join_header_words(input)
            assert res == expect, """
When parsing: '%s'
Expected:     '%s'
Got:          '%s'
Input was:    '%s'""" % (arg, expect, res, input)

if __name__ == "__main__":
    import unittest
    unittest.main()
<commit_msg>Refactor test<commit_after>"""Tests for ClientCookie._HeadersUtil."""

import mechanize._headersutil
from mechanize._testcase import TestCase

class IsHtmlTests(TestCase):

    def test_is_html(self):
        def check(headers, extension, is_html):
            url = "http://example.com/foo" + extension
            self.assertEqual(
                mechanize._headersutil.is_html(headers, url, allow_xhtml),
                is_html)
        for allow_xhtml in False, True:
            check(["text/html"], ".html", True),
            check(["text/html", "text/plain"], ".html", True)
            # Content-type takes priority over file extension from URL
            check(["text/html"], ".txt", True)
            check(["text/plain"], ".html", False)
            # use extension if no Content-Type
            check([], ".html", True)
            check([], ".gif", False)
            # don't regard XHTML as HTML (unless user explicitly asks for it),
            # since we don't yet handle XML properly
            check([], ".xhtml", allow_xhtml)
            check(["text/xhtml"], ".xhtml", allow_xhtml)

class HeaderTests(TestCase):

    def test_parse_ns_headers_expires(self):
        from mechanize._headersutil import parse_ns_headers

        # quotes should be stripped
        assert parse_ns_headers(['foo=bar; expires=01 Jan 2040 22:23:32 GMT']) == \
               [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]]
        assert parse_ns_headers(['foo=bar; expires="01 Jan 2040 22:23:32 GMT"']) == \
               [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]]

    def test_parse_ns_headers_version(self):
        from mechanize._headersutil import parse_ns_headers

        # quotes should be stripped
        expected = [[('foo', 'bar'), ('version', '1')]]
        for hdr in [
            'foo=bar; version="1"',
            'foo=bar; Version="1"',
            ]:
            self.assertEquals(parse_ns_headers([hdr]), expected)

    def test_parse_ns_headers_special_names(self):
        # names such as 'expires' are not special in first name=value pair
        # of Set-Cookie: header
        from mechanize._headersutil import parse_ns_headers

        # Cookie with name 'expires'
        hdr = 'expires=01 Jan 2040 22:23:32 GMT'
        expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
        self.assertEquals(parse_ns_headers([hdr]), expected)

    def test_join_header_words(self):
        from mechanize._headersutil import join_header_words

        assert join_header_words([[
            ("foo", None), ("bar", "baz"), (None, "value")
            ]]) == "foo; bar=baz; value"

        assert join_header_words([[]]) == ""

    def test_split_header_words(self):
        from mechanize._headersutil import split_header_words

        tests = [
            ("foo", [[("foo", None)]]),
            ("foo=bar", [[("foo", "bar")]]),
            ("   foo   ", [[("foo", None)]]),
            ("   foo=   ", [[("foo", "")]]),
            ("   foo=", [[("foo", "")]]),
            ("   foo=   ; ", [[("foo", "")]]),
            ("   foo=   ; bar= baz ", [[("foo", ""), ("bar", "baz")]]),
            ("foo=bar bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
            # doesn't really matter if this next fails, but it works ATM
            ("foo= bar=baz", [[("foo", "bar=baz")]]),
            ("foo=bar;bar=baz", [[("foo", "bar"), ("bar", "baz")]]),
            ('foo bar baz', [[("foo", None), ("bar", None), ("baz", None)]]),
            ("a, b, c", [[("a", None)], [("b", None)], [("c", None)]]),
            (r'foo; bar=baz, spam=, foo="\,\;\"", bar= ',
             [[("foo", None), ("bar", "baz")],
              [("spam", "")], [("foo", ',;"')], [("bar", "")]]),
            ]

        for arg, expect in tests:
            try:
                result = split_header_words([arg])
            except:
                import traceback, StringIO
                f = StringIO.StringIO()
                traceback.print_exc(None, f)
                result = "(error -- traceback follows)\n\n%s" % f.getvalue()
            assert result == expect, """
When parsing: '%s'
Expected:     '%s'
Got:          '%s'
""" % (arg, expect, result)

    def test_roundtrip(self):
        from mechanize._headersutil import split_header_words, join_header_words

        tests = [
            ("foo", "foo"),
            ("foo=bar", "foo=bar"),
            ("   foo   ", "foo"),
            ("foo=", 'foo=""'),
            ("foo=bar bar=baz", "foo=bar; bar=baz"),
            ("foo=bar;bar=baz", "foo=bar; bar=baz"),
            ('foo bar baz', "foo; bar; baz"),
            (r'foo="\"" bar="\\"', r'foo="\""; bar="\\"'),
            ('foo,,,bar', 'foo, bar'),
            ('foo=bar,bar=baz', 'foo=bar, bar=baz'),

            ('text/html; charset=iso-8859-1',
             'text/html; charset="iso-8859-1"'),

            ('foo="bar"; port="80,81"; discard, bar=baz',
             'foo=bar; port="80,81"; discard, bar=baz'),

            (r'Basic realm="\"foo\\\\bar\""',
             r'Basic; realm="\"foo\\\\bar\""')
            ]

        for arg, expect in tests:
            input = split_header_words([arg])
            res = join_header_words(input)
            assert res == expect, """
When parsing: '%s'
Expected:     '%s'
Got:          '%s'
Input was:    '%s'""" % (arg, expect, res, input)

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


<commit_before>"""Test module for pbs client."""
import pbclient
import json
from default import TestDefault
from helpers import *
from mock import patch, MagicMock
from nose.tools import assert_raises
from requests import exceptions
from pbsexceptions import *

class TestHelpers(TestDefault):

    """Test class for pbs.helpers."""

    @patch('pbclient.find_project')
    def test_find_project_by_short_name(self, mock):
        """Test find_project_by_short_name returns a project."""
        mock.return_value = ['project']
        project = find_project_by_short_name('project', pbclient)
        err_msg = "It shoul return: project"
        assert project == 'project', err_msg

    @patch('pbclient.find_project')
    def test_find_project_by_short_name_returns_no_project(self, mock):
        """Test find_project_by_short_name returns a project."""
        mock.return_value = []
        assert_raises(ProjectNotFound,
                      find_project_by_short_name,
                      'project',
                      pbclient)

    @patch('pbclient.find_project')
    def test_find_project_by_short_name_connection_error(self, mock):
        """Test find_project_by_short_name connection_error is raised."""
        mock.side_effect = exceptions.ConnectionError
        assert_raises(exceptions.ConnectionError,
                      find_project_by_short_name,
                      'project',
                      pbclient)

    @patch('helpers.format_error')
    @patch('pbclient.find_project')
    def test_find_project_by_short_name_error(self, mock, mock2):
        """Test find_project_by_short_name error is printed."""
        mock.return_value = self.error
        assert_raises(ProjectNotFound, find_project_by_short_name, 'project',
                      pbclient)

    def test_check_api_error_raises_exception(self):
        """Test check_api_error raises HTTPError exception."""
        error = dict(status='failed', target='diff')
        assert_raises(exceptions.HTTPError, check_api_error, error)

    def test_check_api_error_returns_none(self):
        """Test check_api_error returns none."""
        error = self.error
        error['status'] = 'wrong'
        check_api_error(error)
        error = 'not_a_dict'
        check_api_error(error)

    @patch('pbclient.find_project')
    def test_format_error(self, mock):
        """Test format_error works."""
        e = ProjectNotFound(message="m", error=dict(error="error"))
        assert_raises(SystemExit, format_error, 'pbclient.find_project', e)

    def test_format_json_task(self):
        """Test format_json_task works."""
        tmp = {'key': 'value'}
        res = format_json_task(json.dumps(tmp))
        err_msg = "It should return a JSON object"
        assert type(res) == dict, err_msg
        assert res['key'] == tmp['key'], err_msg

        tmp = "key: value"
        res = format_json_task(tmp)
        err_msg = "It should return a string"
        assert type(res) == str, err_msg
        assert res == tmp, err_msg

    def test_create_task_info(self):
        """Test create_task_info works."""
        task = {'info': {'k': 'v'}}
        res = create_task_info(task)
        assert res == task['info']

        task = {'k': 'v'}
        res = create_task_info(task)
        assert res == task

    def test_enable_auto_throttling(self):
        """Test enable_auto_throttling works."""
        sleep, msg = enable_auto_throttling(range(10), 9)
        assert sleep is True, "Throttling should be enabled"
        assert msg is not None, "Throttling should be enabled"
        sleep, msg = enable_auto_throttling(range(10), 10)
        assert sleep is False, "Throttling should not be enabled"
        assert msg is None, "Throttling should not be enabled"

    def test_pbs_handler(self):
        """Test PbsHandler patterns works."""
        obj = PbsHandler(None, None, None, None, None)
        patterns = ['*/template.html', '*/tutorial.html',
                    '*/long_description.md', '*/results.html']
        assert obj.patterns == patterns, obj.patterns

    @patch('helpers._update_project')
    def test_pbs_handler_on_modified(self, mock):
        """Test PbsHanlder.on_modified works."""
        obj = PbsHandler('config', 'task_presenter', 'results',
                         'long_description', 'tutorial')
        event = MagicMock()
        event.src_path = '/tmp/path.html'
        obj.on_modified(event)
        mock.assert_called_with('config', 'task_presenter', 'results',
                                'long_description', 'tutorial')
<commit_msg>Better docs.<commit_after>"""Test module for pbs client."""
import pbclient
import json
from default import TestDefault
from helpers import *
from mock import patch, MagicMock
from nose.tools import assert_raises
from requests import exceptions
from pbsexceptions import *

class TestHelpers(TestDefault):

    """Test class for pbs.helpers."""

    @patch('pbclient.find_project')
    def test_find_project_by_short_name(self, mock):
        """Test find_project_by_short_name returns a project."""
        mock.return_value = ['project']
        project = find_project_by_short_name('project', pbclient)
        err_msg = "It shoul return: project"
        assert project == 'project', err_msg

    @patch('pbclient.find_project')
    def test_find_project_by_short_name_returns_no_project(self, mock):
        """Test find_project_by_short_name raises ProjectNotFound for all=0."""
        mock.return_value = []
        assert_raises(ProjectNotFound,
                      find_project_by_short_name,
                      'project',
                      pbclient)

    @patch('pbclient.find_project')
    def test_find_project_by_short_name_connection_error(self, mock):
        """Test find_project_by_short_name connection_error is raised."""
        mock.side_effect = exceptions.ConnectionError
        assert_raises(exceptions.ConnectionError,
                      find_project_by_short_name,
                      'project',
                      pbclient)

    @patch('helpers.format_error')
    @patch('pbclient.find_project')
    def test_find_project_by_short_name_error(self, mock, mock2):
        """Test find_project_by_short_name error is printed."""
        mock.return_value = self.error
        assert_raises(ProjectNotFound, find_project_by_short_name, 'project',
                      pbclient)

    def test_check_api_error_raises_exception(self):
        """Test check_api_error raises HTTPError exception."""
        error = dict(status='failed', target='diff')
        assert_raises(exceptions.HTTPError, check_api_error, error)

    def test_check_api_error_returns_none(self):
        """Test check_api_error returns none."""
        error = self.error
        error['status'] = 'wrong'
        check_api_error(error)
        error = 'not_a_dict'
        check_api_error(error)

    @patch('pbclient.find_project')
    def test_format_error(self, mock):
        """Test format_error works."""
        e = ProjectNotFound(message="m", error=dict(error="error"))
        assert_raises(SystemExit, format_error, 'pbclient.find_project', e)

    def test_format_json_task(self):
        """Test format_json_task works."""
        tmp = {'key': 'value'}
        res = format_json_task(json.dumps(tmp))
        err_msg = "It should return a JSON object"
        assert type(res) == dict, err_msg
        assert res['key'] == tmp['key'], err_msg

        tmp = "key: value"
        res = format_json_task(tmp)
        err_msg = "It should return a string"
        assert type(res) == str, err_msg
        assert res == tmp, err_msg

    def test_create_task_info(self):
        """Test create_task_info works."""
        task = {'info': {'k': 'v'}}
        res = create_task_info(task)
        assert res == task['info']

        task = {'k': 'v'}
        res = create_task_info(task)
        assert res == task

    def test_enable_auto_throttling(self):
        """Test enable_auto_throttling works."""
        sleep, msg = enable_auto_throttling(range(10), 9)
        assert sleep is True, "Throttling should be enabled"
        assert msg is not None, "Throttling should be enabled"
        sleep, msg = enable_auto_throttling(range(10), 10)
        assert sleep is False, "Throttling should not be enabled"
        assert msg is None, "Throttling should not be enabled"

    def test_pbs_handler(self):
        """Test PbsHandler patterns works."""
        obj = PbsHandler(None, None, None, None, None)
        patterns = ['*/template.html', '*/tutorial.html',
                    '*/long_description.md', '*/results.html']
        assert obj.patterns == patterns, obj.patterns

    @patch('helpers._update_project')
    def test_pbs_handler_on_modified(self, mock):
        """Test PbsHanlder.on_modified works."""
        obj = PbsHandler('config', 'task_presenter', 'results',
                         'long_description', 'tutorial')
        event = MagicMock()
        event.src_path = '/tmp/path.html'
        obj.on_modified(event)
        mock.assert_called_with('config', 'task_presenter', 'results',
                                'long_description', 'tutorial')
<|endoftext|>