<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseRedirect
from django.db.models import Q

from tickle.models import Person
from fungus.models import ShiftType, Shift, ShiftRegistration, Functionary, Worker, FunctionaryDiscount
from tickle.admin import PersonAdmin, TickleUserInline, PurchaseInline

@admin.register(ShiftType)
class ShiftTypeAdmin(admin.ModelAdmin):
    pass

class ShiftRegistrationInline(admin.TabularInline):
    model = ShiftRegistration
    extra = 0

class ResponsibleListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('responsible person')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'responsible'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        people = set([i.responsible for i in model_admin.model.objects.filter(responsible__isnull=False)])
        return [(i.pk, i.full_name) for i in people]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(responsible__pk__exact=self.value())
        else:
            return queryset

class ShiftTypeListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('shift type')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'shift_type'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        shift_types = set([i.shift_type for i in model_admin.model.objects.all()])
        return [(i.pk, i.__str__) for i in shift_types]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(shift_type__pk__exact=self.value())
        else:
            return queryset

class ShiftStatusListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('status')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('critical', _('Critical')),
            ('alarming', _('Alarming')),
            ('ok', _('OK')),
            ('overstaffed', _('Overstaffed'))
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value() == 'critical':
            return queryset.critical()
        elif self.value() == 'alarming':
            return queryset.alarming()
        elif self.value() == 'ok':
            return queryset.ok()
        elif self.value() == 'overstaffed':
            return queryset.overstaffed()
        else:
            return queryset

@admin.register(Shift)
class ShiftAdmin(admin.ModelAdmin):
    inlines = (ShiftRegistrationInline,)

    date_hierarchy = 'start'
    list_display = ('shift_type', 'start', 'end', 'rendered_registrations', 'people_critical', 'people_alarming', 'people_max', 'responsible', 'public')
    list_display_links = ('shift_type', 'start', 'end')
    list_editable = ('people_max', 'people_alarming', 'people_critical', 'public')
    list_filter = (ShiftTypeListFilter, ShiftStatusListFilter, 'public', ResponsibleListFilter)

    def rendered_registrations(self, obj):
        registrations = obj.registrations.count()
        status = obj.status

        if status == 'critical':
            return '{0}    {1}'.format(registrations, ugettext('Critical'))
        elif status == 'alarming':
            return '{0}    {1}'.format(registrations, ugettext('Alarming'))
        elif status == 'ok':
            return '{0}    {1}'.format(registrations, ugettext('OK'))
        elif status == 'overstaffed':
            return '{0}    {1}'.format(registrations, ugettext('Overstaffed'))

    rendered_registrations.short_description = _('status')
    rendered_registrations.allow_tags = True

class ShiftRegistrationPersonListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('person')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'person'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        people = set([i.person for i in model_admin.model.objects.all()])
        return [(i.pk, i.full_name) for i in people]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(person__pk__exact=self.value())
        else:
            return queryset

@admin.register(ShiftRegistration)
class ShiftRegistrationAdmin(admin.ModelAdmin):
    list_display = ('person', 'shift', 'checked_in', 'checked_out')
    list_filter = (ShiftRegistrationPersonListFilter,)

    actions = ['change_pass_action']

    def change_pass_action(self, request, queryset):
        selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        return HttpResponseRedirect("shifchange/?ids=%s" % ",".join(selected))

    change_pass_action.short_description = "Byt markerade arbetspass"

class FunctionaryInline(admin.StackedInline):
    model = Functionary
    extra = 0
    max_num = 1

@admin.register(Worker)
class WorkerAdmin(PersonAdmin):
    inlines = (FunctionaryInline, ShiftRegistrationInline, TickleUserInline, PurchaseInline,)
    list_display = ('first_name', 'last_name', 'pid', 'email', 'phone', 'liu_id', 'registration_count',
                    'functionary_registered', 'functionary_signed_contract', 'functionary_attended_info_meeting',
                    'functionary_pledge_payed', 'functionary_pledge_returned')

    def has_add_permission(self, request):
        # We should not add people from here.
        return False

    def get_queryset(self, request):
        """
        Returns the original queryset but filters out only registered workers and people with shift registrations
        """
        return super(WorkerAdmin, self).get_queryset(request).workers()

    def functionary_registered(self, obj):
        return obj.functionary.registered or None

    functionary_registered.short_description = _('functionary registered')
    functionary_registered.admin_order_field = 'functionary__registered'

    def functionary_signed_contract(self, obj):
        return obj.functionary.signed_contract or None

    functionary_signed_contract.short_description = _('signed contract')
    functionary_signed_contract.admin_order_field = 'functionary__signed_contract'

    def functionary_attended_info_meeting(self, obj):
        return obj.functionary.attended_info_meeting or None

    functionary_attended_info_meeting.short_description = _('attended info meeting')
    functionary_attended_info_meeting.admin_order_field = 'functionary__attended_info_meeting'

    def functionary_pledge_payed(self, obj):
        return obj.functionary.pledge_payed or None

    functionary_pledge_payed.short_description = _('pledge payed')
    functionary_pledge_payed.admin_order_field = 'functionary__pledge_payed'

    def functionary_pledge_returned(self, obj):
        return obj.functionary.pledge_returned or None

    functionary_pledge_returned.short_description = _('pledge returned')
    functionary_pledge_returned.admin_order_field = 'functionary__pledge_returned'

    def registration_count(self, obj):
        return obj.shift_registrations.count()

    registration_count.short_description = _('shifts')

@admin.register(FunctionaryDiscount)
class FunctionaryDiscountAdmin(admin.ModelAdmin):
    pass
<commit_msg>Pimped up<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseRedirect
from django.db.models import Q

from tickle.models import Person
from fungus.models import ShiftType, Shift, ShiftRegistration, Functionary, Worker, FunctionaryDiscount
from tickle.admin import PersonAdmin, TickleUserInline, PurchaseInline

@admin.register(ShiftType)
class ShiftTypeAdmin(admin.ModelAdmin):
    pass

class ShiftRegistrationInline(admin.TabularInline):
    model = ShiftRegistration
    extra = 0

class ResponsibleListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('responsible person')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'responsible'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        people = set([i.responsible for i in model_admin.model.objects.filter(responsible__isnull=False)])
        return [(i.pk, i.full_name) for i in people]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(responsible__pk__exact=self.value())
        else:
            return queryset

class ShiftTypeListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('shift type')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'shift_type'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        shift_types = set([i.shift_type for i in model_admin.model.objects.all()])
        return [(i.pk, i.__str__) for i in shift_types]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(shift_type__pk__exact=self.value())
        else:
            return queryset

class ShiftStatusListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('status')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('critical', _('Critical')),
            ('alarming', _('Alarming')),
            ('ok', _('OK')),
            ('overstaffed', _('Overstaffed'))
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value() == 'critical':
            return queryset.critical()
        elif self.value() == 'alarming':
            return queryset.alarming()
        elif self.value() == 'ok':
            return queryset.ok()
        elif self.value() == 'overstaffed':
            return queryset.overstaffed()
        else:
            return queryset

@admin.register(Shift)
class ShiftAdmin(admin.ModelAdmin):
    inlines = (ShiftRegistrationInline,)

    date_hierarchy = 'start'
    list_display = ('shift_type', 'start', 'end', 'rendered_registrations', 'people_critical', 'people_alarming', 'people_max', 'responsible', 'public')
    list_display_links = ('shift_type', 'start', 'end')
    list_editable = ('people_max', 'people_alarming', 'people_critical', 'public')
    list_filter = (ShiftTypeListFilter, ShiftStatusListFilter, 'public', ResponsibleListFilter)

    def rendered_registrations(self, obj):
        registrations = obj.registrations.count()
        status = obj.status

        if status == 'critical':
            return '{0}    {1}'.format(registrations, ugettext('Critical'))
        elif status == 'alarming':
            return '{0}    {1}'.format(registrations, ugettext('Alarming'))
        elif status == 'ok':
            return '{0}    {1}'.format(registrations, ugettext('OK'))
        elif status == 'overstaffed':
            return '{0}    {1}'.format(registrations, ugettext('Overstaffed'))

    rendered_registrations.short_description = _('status')
    rendered_registrations.allow_tags = True

class ShiftRegistrationPersonListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('person')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'person'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        people = set([i.person for i in model_admin.model.objects.all()])
        return [(i.pk, i.full_name) for i in people]

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        if self.value():
            return queryset.filter(person__pk__exact=self.value())
        else:
            return queryset

@admin.register(ShiftRegistration)
class ShiftRegistrationAdmin(admin.ModelAdmin):
    list_display = ('person', 'shift', 'checked_in', 'checked_out')
    list_filter = (ShiftRegistrationPersonListFilter,)

    actions = ['change_pass_action']

    def change_pass_action(self, request, queryset):
        selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        return HttpResponseRedirect("shifchange/?ids=%s" % ",".join(selected))

    change_pass_action.short_description = "Byt markerade arbetspass"

class FunctionaryInline(admin.StackedInline):
    model = Functionary
    extra = 0
    max_num = 1

class ShiftListFilter(admin.SimpleListFilter):
    title = _('shift')

    parameter_name = 'shift'

    def lookups(self, request, model_admin):
        return [(i.pk, i) for i in Shift.objects.all()]

    def queryset(self, request, queryset):
        if self.value():
            shift = Shift.objects.get(pk=self.value())
            return queryset.filter(shift_registrations__shift=shift)
        else:
            return queryset

@admin.register(Worker)
class WorkerAdmin(PersonAdmin):
    change_list_template = 'admin/tickle/person/change_list.html'
    inlines = (FunctionaryInline, ShiftRegistrationInline, TickleUserInline, PurchaseInline,)
    list_display = ('first_name', 'last_name', 'pid', 'email', 'phone', 'liu_id', 'registration_count',
                    'functionary_registered', 'functionary_signed_contract', 'functionary_attended_info_meeting',
                    'functionary_pledge_payed', 'functionary_pledge_returned', 'special_nutrition_render')

    list_filter = ('special_nutrition', ShiftListFilter)

    def has_add_permission(self, request):
        # We should not add people from here.
        return False

    def get_queryset(self, request):
        """
        Returns the original queryset but filters out only registered workers and people with shift registrations
        """
        return super(WorkerAdmin, self).get_queryset(request).workers()

    def functionary_registered(self, obj):
        return obj.functionary.registered or None

    functionary_registered.short_description = _('functionary registered')
    functionary_registered.admin_order_field = 'functionary__registered'

    def functionary_signed_contract(self, obj):
        return obj.functionary.signed_contract or None

    functionary_signed_contract.short_description = _('signed contract')
    functionary_signed_contract.admin_order_field = 'functionary__signed_contract'

    def functionary_attended_info_meeting(self, obj):
        return obj.functionary.attended_info_meeting or None

    functionary_attended_info_meeting.short_description = _('attended info meeting')
    functionary_attended_info_meeting.admin_order_field = 'functionary__attended_info_meeting'

    def functionary_pledge_payed(self, obj):
        return obj.functionary.pledge_payed or None

    functionary_pledge_payed.short_description = _('pledge payed')
    functionary_pledge_payed.admin_order_field = 'functionary__pledge_payed'

    def functionary_pledge_returned(self, obj):
        return obj.functionary.pledge_returned or None

    functionary_pledge_returned.short_description = _('pledge returned')
    functionary_pledge_returned.admin_order_field = 'functionary__pledge_returned'

    def registration_count(self, obj):
        return obj.shift_registrations.count()

    registration_count.short_description = _('shifts')

@admin.register(FunctionaryDiscount)
class FunctionaryDiscountAdmin(admin.ModelAdmin):
    pass
<|endoftext|>


<commit_before>"""
Notebooks tests
----------------

Execute all notebooks.

"""

import io
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.exporters import Exporter, HTMLExporter

def notebook_tester(fname):
    raw_nb = Exporter().from_filename(fname)
    raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = 'python'
    preproc = ExecutePreprocessor(timeout=-1)
    try:
        exec_nb = preproc.preprocess(*raw_nb)
    except Exception as e:
        return '[Failed]\n{}'.format(e)

    out_nb = HTMLExporter().from_notebook_node(*exec_nb)
    fout = fname.replace('.ipynb', '.html')
    with io.open(fout, 'w') as f:
        f.write(out_nb[0])
    return '[Passed]'

if __name__ == '__main__':
    import os
    import sys
    import glob

    rootpath = os.path.join(os.path.abspath(os.path.pardir), 'notebooks')
    nblist = glob.glob(os.path.join(rootpath, '*.ipynb'))

    fail = False
    for ipynb in sorted(nblist):
        print('[Running notebook]: {}'.format(ipynb))
        if '2017-01-23-R-notebook.ipynb' in ipynb:
            continue
        ret = notebook_tester(ipynb)
        if 'Failed' in ret:
            fail = True
        print('{}\n'.format(ret))
    if fail:
        sys.exit(1)
    else:
        sys.exit(0)
<commit_msg>Test R notebook<commit_after>"""
Notebooks tests
----------------

Execute all notebooks.

"""

import io
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.exporters import Exporter, HTMLExporter

def notebook_tester(fname, kernelspec='python'):
    raw_nb = Exporter().from_filename(fname)
    raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = kernelspec
    preproc = ExecutePreprocessor(timeout=-1)
    try:
        exec_nb = preproc.preprocess(*raw_nb)
    except Exception as e:
        return '[Failed]\n{}'.format(e)

    out_nb = HTMLExporter().from_notebook_node(*exec_nb)
    fout = fname.replace('.ipynb', '.html')
    with io.open(fout, 'w') as f:
        f.write(out_nb[0])
    return '[Passed]'

if __name__ == '__main__':
    import os
    import sys
    import glob

    rootpath = os.path.join(os.path.abspath(os.path.pardir), 'notebooks')
    nblist = glob.glob(os.path.join(rootpath, '*.ipynb'))

    fail = False
    for ipynb in sorted(nblist):
        print('[Running notebook]: {}'.format(ipynb))
        if '2017-01-23-R-notebook.ipynb' in ipynb:
            kernelspec = 'ir'
        else:
            kernelspec = 'python'
        ret = notebook_tester(ipynb)
        if 'Failed' in ret:
            fail = True
        print('{}\n'.format(ret))
    if fail:
        sys.exit(1)
    else:
        sys.exit(0)
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
"""NTP offset collectd plugin tests"""

from __future__ import division, with_statement
import collections
import contextlib
import datetime
import mock
import unittest

from dns.exception import DNSException
import ntplib

class MockConfig(mock.Mock):

    def __init__(self, **kwargs):
        super(MockConfig, self).__init__()
        self.children = [
            mock.Mock(key=key, values=values)
            for key, values in kwargs.iteritems()]

test_pool = [
    '0.0.0.0',
    '1.1.1.1']

Metrics = collections.namedtuple('Metrics', ('avg', 'min', 'max'))
ExpectedMetric = collections.namedtuple('ExpectedMetric', (
    'type_instance', 'values'))

def mock_metrics():
    return Metrics(mock.Mock(), mock.Mock(), mock.Mock())

@contextlib.contextmanager
def dns_query(answer=[]):
    with mock.patch('ntpoffset.dns') as dns:
        query = dns.resolver.query
        reply = query.return_value
        reply.response.answer = [
            mock.Mock(items=[
                mock.Mock(address=address) for address in answer])]
        yield query

@contextlib.contextmanager
def ntp_offsets(offsets):
    with mock.patch('ntplib.NTPClient') as NTPClient:
        ntp_client = NTPClient.return_value
        ntp_client.request.side_effect = [
            mock.Mock(offset=offset) for offset in offsets]
        yield ntp_client.request

def raise_exception(exc):

    def fn(*args, **kwargs):
        raise exc

    return fn

class NtpOffsetPluginTest(unittest.TestCase):

    def setUp(self):
        self.collectd = mock.Mock()
        self.modules_patch = mock.patch.dict(
            'sys.modules', {'collectd': self.collectd})
        self.modules_patch.start()
        import ntpoffset
        self.ntpoffset = ntpoffset

    def tearDown(self):
        self.modules_patch.stop()

    def plugin(self, *args):
        return self.ntpoffset.NtpOffset(*args)

    def test_plugin_identifies_itself(self):
        self.assertEqual('ntpoffset', self.plugin().PLUGIN_NAME)

    def test_minimal_config_requires_pool_name(self):
        try:
            self.plugin(MockConfig(foo=[]))
        except self.ntpoffset.NtpOffsetConfigException:
            pass
        else:
            self.fail('NtpOffsetConfigException not raised')

    def test_minimal_config_is_valid(self):
        try:
            self.plugin(MockConfig(pool=['127.0.0.1']))
        except Exception as e:
            self.fail(e)

    def test_plugin_queries_each_server_in_pool(self):
        addr = '127.0.0.1'
        config = MockConfig(pool=[addr])
        offsets = range(len(test_pool))

        with dns_query(test_pool) as dns_resolver:
            with ntp_offsets(offsets) as ntp_request:

                self.plugin(config).read()

                dns_resolver.assert_called_with(addr, 'A')

                ntp_request.assert_has_calls([
                    mock.call(address)
                    for address in test_pool])

    def test_metric_is_avg_min_and_max_offset(self):
        config = MockConfig(pool=['127.0.0.1'])
        offsets = [-0.13579, 0.2468]
        expected = [
            ExpectedMetric('average', [sum(offsets) / len(offsets)]),
            ExpectedMetric('min', [min(offsets)]),
            ExpectedMetric('max', [max(offsets)])
        ]

        with ntp_offsets(offsets):
            with dns_query(test_pool):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                for metric, expected in zip(metrics, expected):
                    assert metric.dispatch.called
                    self.assertEqual(
                        expected.type_instance, metric.type_instance)
                    self.assertEqual(expected.values, metric.values)

    def test_nothing_submitted_if_no_pool_servers(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query([]) as dns_resolver:

            dns_resolver.side_effect = raise_exception(
                DNSException('Some DNS problem'))

            self.plugin(config).read()

            self.collectd.Values.assert_has_calls([])

    def test_nothing_submitted_if_no_servers_respond(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([None, None]) as ntp_request:

                ntp_request.side_effect = raise_exception(
                    ntplib.NTPException('No response received from host.'))

                self.plugin(config).read()

                self.collectd.Values.assert_has_calls([])

    def test_metric_submitted_if_at_least_one_server_responds(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([None, 0.13579]):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                for metric in metrics:
                    self.assertEqual([0.13579], metric.values)

    def test_metric_has_unix_timestamp(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([0.1234, 0.2345]):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                now = datetime.datetime.now()
                tolerance = datetime.timedelta(seconds=3)
                for metric in metrics:
                    time = datetime.datetime.utcfromtimestamp(metric.time)
                    self.assertLess(tolerance, now - time)
<commit_msg>Fix assertion for py2.6<commit_after># -*- encoding: utf-8 -*-
"""NTP offset collectd plugin tests"""

from __future__ import division, with_statement
import collections
import contextlib
import datetime
import mock
import unittest

from dns.exception import DNSException
import ntplib

class MockConfig(mock.Mock):

    def __init__(self, **kwargs):
        super(MockConfig, self).__init__()
        self.children = [
            mock.Mock(key=key, values=values)
            for key, values in kwargs.iteritems()]

test_pool = [
    '0.0.0.0',
    '1.1.1.1']

Metrics = collections.namedtuple('Metrics', ('avg', 'min', 'max'))
ExpectedMetric = collections.namedtuple('ExpectedMetric', (
    'type_instance', 'values'))

def mock_metrics():
    return Metrics(mock.Mock(), mock.Mock(), mock.Mock())

@contextlib.contextmanager
def dns_query(answer=[]):
    with mock.patch('ntpoffset.dns') as dns:
        query = dns.resolver.query
        reply = query.return_value
        reply.response.answer = [
            mock.Mock(items=[
                mock.Mock(address=address) for address in answer])]
        yield query

@contextlib.contextmanager
def ntp_offsets(offsets):
    with mock.patch('ntplib.NTPClient') as NTPClient:
        ntp_client = NTPClient.return_value
        ntp_client.request.side_effect = [
            mock.Mock(offset=offset) for offset in offsets]
        yield ntp_client.request

def raise_exception(exc):

    def fn(*args, **kwargs):
        raise exc

    return fn

class NtpOffsetPluginTest(unittest.TestCase):

    def setUp(self):
        self.collectd = mock.Mock()
        self.modules_patch = mock.patch.dict(
            'sys.modules', {'collectd': self.collectd})
        self.modules_patch.start()
        import ntpoffset
        self.ntpoffset = ntpoffset

    def tearDown(self):
        self.modules_patch.stop()

    def plugin(self, *args):
        return self.ntpoffset.NtpOffset(*args)

    def test_plugin_identifies_itself(self):
        self.assertEqual('ntpoffset', self.plugin().PLUGIN_NAME)

    def test_minimal_config_requires_pool_name(self):
        try:
            self.plugin(MockConfig(foo=[]))
        except self.ntpoffset.NtpOffsetConfigException:
            pass
        else:
            self.fail('NtpOffsetConfigException not raised')

    def test_minimal_config_is_valid(self):
        try:
            self.plugin(MockConfig(pool=['127.0.0.1']))
        except Exception as e:
            self.fail(e)

    def test_plugin_queries_each_server_in_pool(self):
        addr = '127.0.0.1'
        config = MockConfig(pool=[addr])
        offsets = range(len(test_pool))

        with dns_query(test_pool) as dns_resolver:
            with ntp_offsets(offsets) as ntp_request:

                self.plugin(config).read()

                dns_resolver.assert_called_with(addr, 'A')

                ntp_request.assert_has_calls([
                    mock.call(address)
                    for address in test_pool])

    def test_metric_is_avg_min_and_max_offset(self):
        config = MockConfig(pool=['127.0.0.1'])
        offsets = [-0.13579, 0.2468]
        expected = [
            ExpectedMetric('average', [sum(offsets) / len(offsets)]),
            ExpectedMetric('min', [min(offsets)]),
            ExpectedMetric('max', [max(offsets)])
        ]

        with ntp_offsets(offsets):
            with dns_query(test_pool):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                for metric, expected in zip(metrics, expected):
                    assert metric.dispatch.called
                    self.assertEqual(
                        expected.type_instance, metric.type_instance)
                    self.assertEqual(expected.values, metric.values)

    def test_nothing_submitted_if_no_pool_servers(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query([]) as dns_resolver:

            dns_resolver.side_effect = raise_exception(
                DNSException('Some DNS problem'))

            self.plugin(config).read()

            self.collectd.Values.assert_has_calls([])

    def test_nothing_submitted_if_no_servers_respond(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([None, None]) as ntp_request:

                ntp_request.side_effect = raise_exception(
                    ntplib.NTPException('No response received from host.'))

                self.plugin(config).read()

                self.collectd.Values.assert_has_calls([])

    def test_metric_submitted_if_at_least_one_server_responds(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([None, 0.13579]):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                for metric in metrics:
                    self.assertEqual([0.13579], metric.values)

    def test_metric_has_unix_timestamp(self):
        config = MockConfig(pool=['127.0.0.1'])

        with dns_query(test_pool):
            with ntp_offsets([0.1234, 0.2345]):

                metrics = mock_metrics()
                self.collectd.Values.side_effect = metrics

                self.plugin(config).read()

                now = datetime.datetime.now()
                tolerance = datetime.timedelta(seconds=3)
                for metric in metrics:
                    time = datetime.datetime.utcfromtimestamp(metric.time)
                    self.assertTrue(tolerance > now - time)
<|endoftext|>


<commit_before>"""
Module is responsible for handling of game/business logic behind 'I Refuse'

 Author: Jacob Delgado
 Date: Mar 6, 2016
"""
import random
import sys

from game.player import Players

class Game(object):
    """
    The game logic behind 'I Refuse.'
    """
    USER_PASSES = 1
    USER_TAKES_CARD = 2

    def __init__(self):
        self.cards = []
        self.players = None

    def setup(self, input_func):
        """
        Sets up the card game.

        :param input_func: The function to use to prompt the user with.
        :return: None
        """
        self.cards = self.setup_cards()
        self.players = self.setup_players(input_func)

    @staticmethod
    def setup_players(input_func):
        """
        Sets up the number of players. Must be between 3-5.

        :param input_func: Used for mocking input()
        :return: A list of game.player.Player objects
        """
        sys.stdout.write("Enter the number of players [3-5]: ")
        number_of_people_playing = int(input_func())
        if number_of_people_playing < 3 or number_of_people_playing > 5:
            raise AssertionError("invalid number of players")
        return Players(number_of_people_playing)

    @staticmethod
    def setup_cards():
        """
        :return: A list of randomized 24 cards ranging from 3-35.
        """
        return random.sample(range(3, 36), 24)

    def determine_winner(self):
        """
        Calculate who won. Ties can occur.

        :return: The list of winners.
        """
        player_totals = {}
        for player in self.players:
            if player.calculate_points() in player_totals:
                player_totals[player.calculate_points()].append(player)
            else:
                player_totals[player.calculate_points()] = [player]

        sorted_totals = sorted(player_totals.keys())
        return player_totals[sorted_totals[0]]

    def play(self, input_func):
        """
        Business logic for I Refuse. Coordinates how the game is played.

        :param input_func: Input function to prompt the user.
        :return: The list of winners after a game has been completed.
        """
        max_flips = len(self.cards)
        player = self.players.next_player()
        for _ in range(max_flips):
            card = self.flip_card()
            tokens = 0
            action = self.prompt_for_action(card, tokens, input_func, player)

            while action == Game.USER_PASSES:
                tokens += 1
                player.passes()
                player = self.players.next_player(player)
                action = self.prompt_for_action(card, tokens, input_func,
                                                player)
            player.take_card(card, tokens)

        return self.determine_winner()

    def prompt_for_action(self, card, tokens, input_func, current_player):
        """
        Prompts the user for action, returns true if the user takes a cards,
        false otherwise.

        :param card: The card currently face up.
        :param tokens: The amount of tokens on the face up card.
        :param input_func: Prompt for user input.
        :param current_player: The player whose action it is.
        :return: True if the user took the card, false if not.
        """
        if not current_player.can_pass():
            return Game.USER_TAKES_CARD

        action = 0
        for player in self.players:
            print(player.stats())
        while not (action == Game.USER_PASSES or action == Game.USER_TAKES_CARD):
            print("\n{} it is your turn".format(current_player))
            print("Available card: {}, Number of tokens: {}"
                  .format(card, tokens))
            print("What action do you wish to perform: ")
            print("{}. Pass".format(Game.USER_PASSES))
            print("{}. Take card".format(Game.USER_TAKES_CARD))
            print("------------")
            sys.stdout.write("Selection: ")
            action = int(input_func())

        return action

    def flip_card(self):
        """
        Flips the top card on the deck

        :return: The newest card to be face up.
        """
        return self.cards.pop()

<commit_msg>code cleanup<commit_after>"""
Module is responsible for handling of game/business logic behind 'I Refuse'

 Author: Jacob Delgado
 Date: Mar 6, 2016
"""
import random
import sys

from game.player import Players

class Game(object):
    """
    The game logic behind 'I Refuse.'
    """
    USER_PASSES = 1
    USER_TAKES_CARD = 2
    MIN_PLAYERS = 3
    MAX_PLAYERS = 5
    NUMBER_OF_ROUNDS = 24
    MIN_CARD = 3
    MAX_CARD = 36

    def __init__(self):
        self.cards = []
        self.players = None

    def setup(self, input_func):
        """
        Sets up the card game.

        :param input_func: The function to use to prompt the user with.
        :return: None
        """
        self.cards = self.setup_cards()
        self.players = self.setup_players(input_func)

    @staticmethod
    def setup_players(input_func):
        """
        Sets up the number of players. Must be between 3-5.

        :param input_func: Used for mocking input()
        :return: A list of game.player.Player objects
        """
        sys.stdout.write("Enter the number of players [3-5]: ")
        number_of_people_playing = int(input_func())
        if number_of_people_playing < Game.MIN_PLAYERS or \
                number_of_people_playing > Game.MAX_PLAYERS:
            raise AssertionError("invalid number of players")
        return Players(number_of_people_playing)

    @staticmethod
    def setup_cards():
        """
        :return: A list of randomized 24 cards ranging from 3-35.
        """
        return random.sample(range(Game.MIN_CARD, Game.MAX_CARD),
                             Game.NUMBER_OF_ROUNDS)

    def determine_winner(self):
        """
        Calculate who won. Ties can occur.

        :return: The list of winners.
        """
        player_totals = {}
        for player in self.players:
            if player.calculate_points() in player_totals:
                player_totals[player.calculate_points()].append(player)
            else:
                player_totals[player.calculate_points()] = [player]

        sorted_totals = sorted(player_totals.keys())
        return player_totals[sorted_totals[0]]

    def play(self, input_func):
        """
        Business logic for I Refuse. Coordinates how the game is played.

        :param input_func: Input function to prompt the user.
        :return: The list of winners after a game has been completed.
        """
        max_flips = len(self.cards)
        player = self.players.next_player()
        for _ in range(max_flips):
            card = self.flip_card()
            tokens = 0
            action = self.prompt_for_action(card, tokens, input_func, player)

            while action == Game.USER_PASSES:
                tokens += 1
                player.passes()
                player = self.players.next_player(player)
                action = self.prompt_for_action(card, tokens, input_func,
                                                player)
            player.take_card(card, tokens)

        return self.determine_winner()

    def prompt_for_action(self, card, tokens, input_func, current_player):
        """
        Prompts the user for action, returns true if the user takes a cards,
        false otherwise.

        :param card: The card currently face up.
        :param tokens: The amount of tokens on the face up card.
        :param input_func: Prompt for user input.
        :param current_player: The player whose action it is.
        :return: True if the user took the card, false if not.
        """
        if not current_player.can_pass():
            return Game.USER_TAKES_CARD

        action = 0
        for player in self.players:
            print(player.stats())
        while not (action == Game.USER_PASSES or
                   action == Game.USER_TAKES_CARD):
            print("\n{} it is your turn".format(current_player))
            print("Available card: {}, Number of tokens: {}"
                  .format(card, tokens))
            print("What action do you wish to perform: ")
            print("{}. Pass".format(Game.USER_PASSES))
            print("{}. Take card".format(Game.USER_TAKES_CARD))
            print("------------")
            sys.stdout.write("Selection: ")
            action = int(input_func())

        return action

    def flip_card(self):
        """
        Flips the top card on the deck

        :return: The newest card to be face up.
        """
        return self.cards.pop()
<|endoftext|>


<commit_before># -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab

import pygtk
pygtk.require("2.0")

import unittest

import sys
sys.path.insert(0, "../")

from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import Gtk
import gi.overrides as overrides

class TestGdk(unittest.TestCase):

    def test_color(self):
        color = Gdk.Color(100, 200, 300)
        self.assertEquals(color.red, 100)
        self.assertEquals(color.green, 200)
        self.assertEquals(color.blue, 300)

    def test_event(self):
        event = Gdk.Event.new(Gdk.EventType.CONFIGURE)
        self.assertEquals(event.type, Gdk.EventType.CONFIGURE)
        self.assertEquals(event.send_event, 0)

        event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION)
        event.x_root, event.y_root = 0, 5
        self.assertEquals(event.x_root, 0)
        self.assertEquals(event.y_root, 5)

class TestGtk(unittest.TestCase):
    def test_uimanager(self):
        self.assertEquals(Gtk.UIManager, overrides.Gtk.UIManager)
        ui = Gtk.UIManager()
        ui.add_ui_from_string(
"""
<ui>
    <menubar name="menubar1"></menubar>
</ui>
"""
)
        menubar = ui.get_widget("/menubar1")
        self.assertEquals(type(menubar), Gtk.MenuBar)

    def test_actiongroup(self):
        self.assertEquals(Gtk.ActionGroup, overrides.Gtk.ActionGroup)
        action_group = Gtk.ActionGroup (name = 'TestActionGroup')
        callback_data = "callback data"

        def test_action_callback_data(action, user_data):
            self.assertEquals(user_data, callback_data);

        def test_radio_action_callback_data(action, current, user_data):
            self.assertEquals(user_data, callback_data);

        action_group.add_actions ([
            ('test-action1', None, 'Test Action 1',
             None, None, test_action_callback_data),
            ('test-action2', Gtk.STOCK_COPY, 'Test Action 2',
              None, None, test_action_callback_data)], callback_data)
        action_group.add_toggle_actions([
            ('test-toggle-action1', None, 'Test Toggle Action 1',
             None, None, test_action_callback_data, False),
            ('test-toggle-action2', Gtk.STOCK_COPY, 'Test Toggle Action 2',
              None, None, test_action_callback_data, True)], callback_data)
        action_group.add_radio_actions([
            ('test-radio-action1', None, 'Test Radio Action 1'),
            ('test-radio-action2', Gtk.STOCK_COPY, 'Test Radio Action 2')], 1,
            test_radio_action_callback_data,
            callback_data)

        expected_results = (('test-action1', Gtk.Action),
                            ('test-action2', Gtk.Action),
                            ('test-toggle-action1', Gtk.ToggleAction),
                            ('test-toggle-action2', Gtk.ToggleAction),
                            ('test-radio-action1', Gtk.RadioAction),
                            ('test-radio-action2', Gtk.RadioAction))

        for action, cmp in zip(action_group.list_actions(), expected_results):
            a = (action.get_name(), type(action))
            self.assertEquals(a,cmp)
            action.activate()

    def test_builder(self):
        self.assertEquals(Gtk.Builder, overrides.Gtk.Builder)

        class SignalTest(GObject.GObject):
            __gtype_name__ = "GIOverrideSignalTest"
            __gsignals__ = {
                "test-signal": (GObject.SIGNAL_RUN_FIRST,
                                GObject.TYPE_NONE,
                                []),
            }

        class SignalCheck:
            def __init__(self):
                self.sentinel = 0

            def on_signal_1(self, *args):
                self.sentinel += 1

            def on_signal_3(self, *args):
                self.sentinel += 3

        signal_checker = SignalCheck()
        builder = Gtk.Builder()

        # add object1 to the builder
        builder.add_from_string(
"""
<interface>
  <object class="GIOverrideSignalTest" id="object1">
      <signal name="test-signal" handler="on_signal_1" />
  </object>
</interface>
""")

        # only add object3 to the builder
        builder.add_objects_from_string(
"""
<interface>
  <object class="GIOverrideSignalTest" id="object2">
      <signal name="test-signal" handler="on_signal_2" />
  </object>
  <object class="GIOverrideSignalTest" id="object3">
      <signal name="test-signal" handler="on_signal_3" />
  </object>
  <object class="GIOverrideSignalTest" id="object4">
      <signal name="test-signal" handler="on_signal_4" />
  </object>
</interface>

""",
            ['object3'])

        # hook up signals
        builder.connect_signals(signal_checker)

        # call their notify signals and check sentinel
        objects = builder.get_objects()
        self.assertEquals(len(objects), 2)
        for obj in objects:
            obj.emit('test-signal')

        self.assertEquals(signal_checker.sentinel, 4)

    def test_dialog(self):
        self.assertEquals(Gtk.Dialog, overrides.Gtk.Dialog)
        dialog = Gtk.Dialog (title='Foo',
                             flags=Gtk.DialogFlags.MODAL,
                             buttons=('test-button1', 1))

        dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)

        self.assertEquals('Foo', dialog.get_title())
        self.assertTrue(dialog.get_modal())
        button = dialog.get_widget_for_response (1)
        self.assertEquals('test-button1', button.get_label())
        button = dialog.get_widget_for_response (2)
        self.assertEquals('test-button2', button.get_label())
        button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
        self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())

    class TestClass(GObject.GObject):
        __gtype_name__ = "GIOverrideTreeAPITest"

        def __init__(self, tester, int_value, string_value):
            super(TestGtk.TestClass, self).__init__()
            self.tester = tester
            self.int_value = int_value
            self.string_value = string_value

        def check(self, int_value, string_value):
            self.tester.assertEquals(int_value, self.int_value)
            self.tester.assertEquals(string_value, self.string_value)

    def test_tree_store(self):
        self.assertEquals(Gtk.TreeStore, overrides.Gtk.TreeStore)
        self.assertEquals(Gtk.ListStore, overrides.Gtk.ListStore)
        self.assertEquals(Gtk.TreeModel, overrides.Gtk.TreeModel)
        self.assertEquals(Gtk.TreeViewColumn, overrides.Gtk.TreeViewColumn)

        tree_store = Gtk.TreeStore(int, 'gchararray', TestGtk.TestClass)
        parent = None
        for i in xrange(100):
            label = 'this is child #%d' % i
            testobj = TestGtk.TestClass(self, i, label)
            parent = tree_store.append(parent, (i, label, testobj))

        # len gets the number of children in the root node
        # since we kept appending to the previous node
        # there should only be one child of the root
        self.assertEquals(len(tree_store), 1)

        # walk the tree to see if the values were stored correctly
        parent = None
        i = 0

        (has_children, treeiter) = tree_store.iter_children(parent)
        while (has_children):
           i = tree_store.get_value(treeiter, 0)
           s = tree_store.get_value(treeiter, 1)
           obj = tree_store.get_value(treeiter, 2)
           obj.check(i, s)
           parent = treeiter
           (has_children, treeiter) = tree_store.iter_children(parent)

        self.assertEquals(i, 99)

    def test_list_store(self):
        list_store = Gtk.ListStore(int, str, 'GIOverrideTreeAPITest')
        for i in xrange(100):
            label = 'this is row #%d' % i
            testobj = TestGtk.TestClass(self, i, label)
            parent = list_store.append((i, label, testobj))

        self.assertEquals(len(list_store), 100)

        # walk the list to see if the values were stored correctly
        i = 0
        (has_more, treeiter) = list_store.get_iter_first()

        while has_more:
            i = list_store.get_value(treeiter, 0)
            s = list_store.get_value(treeiter, 1)
            obj = list_store.get_value(treeiter, 2)
            obj.check(i, s)
            has_more = list_store.iter_next(treeiter)

        self.assertEquals(i, 99)

    def test_tree_view_column(self):
        cell = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn(title='This is just a test',
                                    cell_renderer=cell,
                                    text=0,
                                    style=2)

    def test_text_buffer(self):
        self.assertEquals(Gtk.TextBuffer, overrides.Gtk.TextBuffer)
        buffer = Gtk.TextBuffer()
        tag = buffer.create_tag ('title', font = 'Sans 18')

        self.assertEquals(tag.props.name, 'title')
        self.assertEquals(tag.props.font, 'Sans 18')

        (start, end) = buffer.get_bounds()

        buffer.insert(end, 'HelloHello')
        buffer.insert(end, ' Bob')

        cursor_iter = end.copy()
        cursor_iter.backward_chars(9)
        buffer.place_cursor(cursor_iter)
        buffer.insert_at_cursor(' Jane ')

        (start, end) = buffer.get_bounds()
        text = buffer.get_text(start, end, False)

        self.assertEquals(text, 'Hello Jane Hello Bob')
<commit_msg>Gtk.Button unit tests<commit_after># -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab

import pygtk
pygtk.require("2.0")

import unittest

import sys
sys.path.insert(0, "../")

from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import Gtk
import gi.overrides as overrides

class TestGdk(unittest.TestCase):

    def test_color(self):
        color = Gdk.Color(100, 200, 300)
        self.assertEquals(color.red, 100)
        self.assertEquals(color.green, 200)
        self.assertEquals(color.blue, 300)

    def test_event(self):
        event = Gdk.Event.new(Gdk.EventType.CONFIGURE)
        self.assertEquals(event.type, Gdk.EventType.CONFIGURE)
        self.assertEquals(event.send_event, 0)

        event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION)
        event.x_root, event.y_root = 0, 5
        self.assertEquals(event.x_root, 0)
        self.assertEquals(event.y_root, 5)

class TestGtk(unittest.TestCase):
    def test_uimanager(self):
        self.assertEquals(Gtk.UIManager, overrides.Gtk.UIManager)
        ui = Gtk.UIManager()
        ui.add_ui_from_string(
"""
<ui>
    <menubar name="menubar1"></menubar>
</ui>
"""
)
        menubar = ui.get_widget("/menubar1")
        self.assertEquals(type(menubar), Gtk.MenuBar)

    def test_actiongroup(self):
        self.assertEquals(Gtk.ActionGroup, overrides.Gtk.ActionGroup)
        action_group = Gtk.ActionGroup (name = 'TestActionGroup')
        callback_data = "callback data"

        def test_action_callback_data(action, user_data):
            self.assertEquals(user_data, callback_data);

        def test_radio_action_callback_data(action, current, user_data):
            self.assertEquals(user_data, callback_data);

        action_group.add_actions ([
            ('test-action1', None, 'Test Action 1',
             None, None, test_action_callback_data),
            ('test-action2', Gtk.STOCK_COPY, 'Test Action 2',
              None, None, test_action_callback_data)], callback_data)
        action_group.add_toggle_actions([
            ('test-toggle-action1', None, 'Test Toggle Action 1',
             None, None, test_action_callback_data, False),
            ('test-toggle-action2', Gtk.STOCK_COPY, 'Test Toggle Action 2',
              None, None, test_action_callback_data, True)], callback_data)
        action_group.add_radio_actions([
            ('test-radio-action1', None, 'Test Radio Action 1'),
            ('test-radio-action2', Gtk.STOCK_COPY, 'Test Radio Action 2')], 1,
            test_radio_action_callback_data,
            callback_data)

        expected_results = (('test-action1', Gtk.Action),
                            ('test-action2', Gtk.Action),
                            ('test-toggle-action1', Gtk.ToggleAction),
                            ('test-toggle-action2', Gtk.ToggleAction),
                            ('test-radio-action1', Gtk.RadioAction),
                            ('test-radio-action2', Gtk.RadioAction))

        for action, cmp in zip(action_group.list_actions(), expected_results):
            a = (action.get_name(), type(action))
            self.assertEquals(a,cmp)
            action.activate()

    def test_builder(self):
        self.assertEquals(Gtk.Builder, overrides.Gtk.Builder)

        class SignalTest(GObject.GObject):
            __gtype_name__ = "GIOverrideSignalTest"
            __gsignals__ = {
                "test-signal": (GObject.SIGNAL_RUN_FIRST,
                                GObject.TYPE_NONE,
                                []),
            }

        class SignalCheck:
            def __init__(self):
                self.sentinel = 0

            def on_signal_1(self, *args):
                self.sentinel += 1

            def on_signal_3(self, *args):
                self.sentinel += 3

        signal_checker = SignalCheck()
        builder = Gtk.Builder()

        # add object1 to the builder
        builder.add_from_string(
"""
<interface>
  <object class="GIOverrideSignalTest" id="object1">
      <signal name="test-signal" handler="on_signal_1" />
  </object>
</interface>
""")

        # only add object3 to the builder
        builder.add_objects_from_string(
"""
<interface>
  <object class="GIOverrideSignalTest" id="object2">
      <signal name="test-signal" handler="on_signal_2" />
  </object>
  <object class="GIOverrideSignalTest" id="object3">
      <signal name="test-signal" handler="on_signal_3" />
  </object>
  <object class="GIOverrideSignalTest" id="object4">
      <signal name="test-signal" handler="on_signal_4" />
  </object>
</interface>

""",
            ['object3'])

        # hook up signals
        builder.connect_signals(signal_checker)

        # call their notify signals and check sentinel
        objects = builder.get_objects()
        self.assertEquals(len(objects), 2)
        for obj in objects:
            obj.emit('test-signal')

        self.assertEquals(signal_checker.sentinel, 4)

    def test_dialog(self):
        self.assertEquals(Gtk.Dialog, overrides.Gtk.Dialog)
        dialog = Gtk.Dialog (title='Foo',
                             flags=Gtk.DialogFlags.MODAL,
                             buttons=('test-button1', 1))

        dialog.add_buttons ('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)

        self.assertEquals('Foo', dialog.get_title())
        self.assertTrue(dialog.get_modal())
        button = dialog.get_widget_for_response (1)
        self.assertEquals('test-button1', button.get_label())
        button = dialog.get_widget_for_response (2)
        self.assertEquals('test-button2', button.get_label())
        button = dialog.get_widget_for_response (Gtk.ResponseType.CLOSE)
        self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())

    class TestClass(GObject.GObject):
        __gtype_name__ = "GIOverrideTreeAPITest"

        def __init__(self, tester, int_value, string_value):
            super(TestGtk.TestClass, self).__init__()
            self.tester = tester
            self.int_value = int_value
            self.string_value = string_value

        def check(self, int_value, string_value):
            self.tester.assertEquals(int_value, self.int_value)
            self.tester.assertEquals(string_value, self.string_value)

    def test_tree_store(self):
        self.assertEquals(Gtk.TreeStore, overrides.Gtk.TreeStore)
        self.assertEquals(Gtk.ListStore, overrides.Gtk.ListStore)
        self.assertEquals(Gtk.TreeModel, overrides.Gtk.TreeModel)
        self.assertEquals(Gtk.TreeViewColumn, overrides.Gtk.TreeViewColumn)

        tree_store = Gtk.TreeStore(int, 'gchararray', TestGtk.TestClass)
        parent = None
        for i in xrange(100):
            label = 'this is child #%d' % i
            testobj = TestGtk.TestClass(self, i, label)
            parent = tree_store.append(parent, (i, label, testobj))

        # len gets the number of children in the root node
        # since we kept appending to the previous node
        # there should only be one child of the root
        self.assertEquals(len(tree_store), 1)

        # walk the tree to see if the values were stored correctly
        parent = None
        i = 0

        (has_children, treeiter) = tree_store.iter_children(parent)
        while (has_children):
           i = tree_store.get_value(treeiter, 0)
           s = tree_store.get_value(treeiter, 1)
           obj = tree_store.get_value(treeiter, 2)
           obj.check(i, s)
           parent = treeiter
           (has_children, treeiter) = tree_store.iter_children(parent)

        self.assertEquals(i, 99)

    def test_list_store(self):
        list_store = Gtk.ListStore(int, str, 'GIOverrideTreeAPITest')
        for i in xrange(100):
            label = 'this is row #%d' % i
            testobj = TestGtk.TestClass(self, i, label)
            parent = list_store.append((i, label, testobj))

        self.assertEquals(len(list_store), 100)

        # walk the list to see if the values were stored correctly
        i = 0
        (has_more, treeiter) = list_store.get_iter_first()

        while has_more:
            i = list_store.get_value(treeiter, 0)
            s = list_store.get_value(treeiter, 1)
            obj = list_store.get_value(treeiter, 2)
            obj.check(i, s)
            has_more = list_store.iter_next(treeiter)

        self.assertEquals(i, 99)

    def test_tree_view_column(self):
        cell = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn(title='This is just a test',
                                    cell_renderer=cell,
                                    text=0,
                                    style=2)

    def test_text_buffer(self):
        self.assertEquals(Gtk.TextBuffer, overrides.Gtk.TextBuffer)
        buffer = Gtk.TextBuffer()
        tag = buffer.create_tag ('title', font = 'Sans 18')

        self.assertEquals(tag.props.name, 'title')
        self.assertEquals(tag.props.font, 'Sans 18')

        (start, end) = buffer.get_bounds()

        buffer.insert(end, 'HelloHello')
        buffer.insert(end, ' Bob')

        cursor_iter = end.copy()
        cursor_iter.backward_chars(9)
        buffer.place_cursor(cursor_iter)
        buffer.insert_at_cursor(' Jane ')

        (start, end) = buffer.get_bounds()
        text = buffer.get_text(start, end, False)

        self.assertEquals(text, 'Hello Jane Hello Bob')

    def test_buttons(self):
        self.assertEquals(Gtk.Button, overrides.Gtk.Button)

        # test Gtk.Button
        button = Gtk.Button()
        button = Gtk.Button(stock=Gtk.STOCK_CLOSE)
        self.assertEquals(Gtk.STOCK_CLOSE, button.get_label())
        self.assertTrue(button.get_use_stock())
        self.assertTrue(button.get_use_underline())
<|endoftext|>


<commit_before>from api import API

<commit_msg>Adding version information.<commit_after>__version__ = '0.1'

from api import API

<|endoftext|>


<commit_before>from mappings import Base, ScrapedJob
from mappings.utils import create_engine, install_pgcrypto, create_table, create_user, alter_table_owner
from jobs.pipelines import PostgresPipeline
from jobs.items import JobsItem

from scrapy.exceptions import NotConfigured
from scrapy.utils.test import get_crawler
import pytest
import sqlalchemy  # comes from the sqlalchemy-mappings dependencies
import mock

# use the setup/teardown logic from mappings/test_sessions.py
SUPERUSER = 'postgresql://postgres@localhost:5432/jobdb'
DIRK = 'postgresql://dirk_gently@localhost:5432/jobdb'

@pytest.fixture(scope='module')
def db():
    engine = create_engine(SUPERUSER)
    install_pgcrypto(engine)
    try:
        # if a test fails, then we might have a user left over *shrug*
        create_user(engine, 'dirk_gently')
    except sqlalchemy.exc.ProgrammingError:
        pass

    create_table(engine)
    alter_table_owner(engine, 'dirk_gently', 'scraped-jobs')
    yield engine
    # drop the table we created
    Base.metadata.drop_all(engine)
    # and remove the extension
    engine.execute("""DROP EXTENSION IF EXISTS pgcrypto;""")
    # finally, clean up the created user
    engine.execute("""DROP ROLE IF EXISTS dirk_gently;""")

def test_environment_variable():
    # ensure we get the expected exception when not specifying credentials
    with pytest.raises(NotConfigured):
        PostgresPipeline.from_crawler(get_crawler())

    # and that it works when we do
    crawler = get_crawler(settings_dict={'PG_CREDS': 'frrrrp'})
    assert isinstance(PostgresPipeline.from_crawler(crawler), PostgresPipeline)

def test_initialisation():
    crawler = get_crawler(settings_dict={'PG_CREDS': DIRK})
    pipeline = PostgresPipeline.from_crawler(crawler)
    assert pipeline.stats.get_value('postgresql/add') is None
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') is None

def test_statistics():
    crawler = get_crawler(settings_dict={'PG_CREDS': DIRK})
    pipeline = PostgresPipeline.from_crawler(crawler)
    job = JobsItem(spider='test', url='http://fake/job/advert.html', company='Project Blackwing')

    # create a mock for the db session so we can control the response
    pipeline.session = mock.MagicMock()
    pipeline.session.query.return_value.filter.return_value.one_or_none.return_value = None
    # if the lookup returns nothing, then the new job is added to the db
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') is None

    # if we try and add the same job again we should get an 'ignore'
    # note that the internal response is the DB representation of the job
    ScrapedJob.from_dict(dict(job))
    pipeline.session.query.return_value.filter.return_value.one_or_none.return_value = ScrapedJob.from_dict(dict(job))
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') == 1

    # now if we modify the job, and readd it we should trigger a 'modify'
    job['title'] = 'Test Subject'
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') == 1
    assert pipeline.stats.get_value('postgresql/ignore') == 1
<commit_msg>Add proper db test<commit_after>from mappings import Base, ScrapedJob
from mappings.utils import create_engine, install_pgcrypto, create_table, create_user, alter_table_owner, session_scope
from jobs.pipelines import PostgresPipeline
from jobs.items import JobsItem

from scrapy.exceptions import NotConfigured
from scrapy.utils.test import get_crawler
import pytest
import sqlalchemy  # comes from the sqlalchemy-mappings dependencies
import mock

# use the setup/teardown logic from sqlalchemy-mappings/test_sessions.py
SUPERUSER = 'postgresql://postgres@localhost:5432/jobdb'
DIRK = 'postgresql://dirk_gently@localhost:5432/jobdb'

@pytest.fixture(scope='module')
def db():
    engine = create_engine(SUPERUSER)
    install_pgcrypto(engine)
    try:
        # if a test fails, then we might have a user left over *shrug*
        create_user(engine, 'dirk_gently')
    except sqlalchemy.exc.ProgrammingError:
        pass

    create_table(engine)
    alter_table_owner(engine, 'dirk_gently', 'scraped-jobs')
    yield engine
    # drop the table we created
    Base.metadata.drop_all(engine)
    # and remove the extension
    engine.execute("""DROP EXTENSION IF EXISTS pgcrypto;""")
    # finally, clean up the created user
    engine.execute("""DROP ROLE IF EXISTS dirk_gently;""")

def test_postgres_environment_variable():
    # ensure we get the expected exception when not specifying credentials
    with pytest.raises(NotConfigured):
        PostgresPipeline.from_crawler(get_crawler())

    # and that it works when we do
    crawler = get_crawler(settings_dict={'PG_CREDS': 'frrrrp'})
    assert isinstance(PostgresPipeline.from_crawler(crawler), PostgresPipeline)

def test_postgres_initialisation():
    crawler = get_crawler(settings_dict={'PG_CREDS': DIRK})
    pipeline = PostgresPipeline.from_crawler(crawler)
    assert pipeline.stats.get_value('postgresql/add') is None
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') is None

def test_postgres_statistics():
    crawler = get_crawler(settings_dict={'PG_CREDS': DIRK})
    pipeline = PostgresPipeline.from_crawler(crawler)
    job = JobsItem(spider='test', url='http://fake/job/advert.html', company='Project Blackwing')

    # create a mock for the db session so we can control the response
    pipeline.session = mock.MagicMock()
    pipeline.session.query.return_value.filter.return_value.one_or_none.return_value = None
    # if the lookup returns nothing, then the new job is added to the db
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') is None

    # if we try and add the same job again we should get an 'ignore'
    # note that the internal response is the DB representation of the job
    ScrapedJob.from_dict(dict(job))
    pipeline.session.query.return_value.filter.return_value.one_or_none.return_value = ScrapedJob.from_dict(dict(job))
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') is None
    assert pipeline.stats.get_value('postgresql/ignore') == 1

    # now if we modify the job, and readd it we should trigger a 'modify'
    job['title'] = 'Test Subject'
    pipeline.process_item(job, None)

    assert pipeline.stats.get_value('postgresql/add') == 1
    assert pipeline.stats.get_value('postgresql/modify') == 1
    assert pipeline.stats.get_value('postgresql/ignore') == 1

def test_postgres_insert(db):
    crawler = get_crawler(settings_dict={'PG_CREDS': DIRK})
    pipeline = PostgresPipeline.from_crawler(crawler)
    test_subject = JobsItem(spider='a', url='http://subject.html', company='Project Blackwing', title='Test Subject')
    director = JobsItem(spider='a', url='http://director.html', company='Project Blackwing', title='Director')

    # we don't need to provide the `spider` since it's not used, but is required for the inherited
    # function signature
    spider = None
    pipeline.open_spider(spider)
    # as above, the `spider` argument isn't used, but required for the inherited signature
    pipeline.process_item(test_subject, spider)
    pipeline.process_item(director, spider)
    pipeline.close_spider(spider)

    # similar to tests in sqlalchmey-mappings/test_sessions.py
    with session_scope(DIRK) as db_session:
        query = db_session.query(ScrapedJob).filter(ScrapedJob.url == 'http://subject.html')
        result = query.one()
        assert result.url == test_subject['url']
        assert result.data == dict(test_subject)

        query = db_session.query(ScrapedJob).filter(ScrapedJob.url == 'http://director.html')
        result = query.one()
        assert result.url == director['url']
        assert result.spider == director['spider']
        assert result.data == dict(director)
<|endoftext|>


<commit_before>__version__ = '1.1'

from api import Instamojo

<commit_msg>Used relative import for Py3 compatibility and good practice.<commit_after>__version__ = '1.1'

from .api import Instamojo<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import mock
import struct
import uuid
import io
from rawdisk.util.rawstruct import RawStruct

class TestRawStruct(unittest.TestCase):
    def setUp(self):
        self.sample_data = b'\xa1\xb1\xc1\xd1\xe1\xf1\xb1\xa1\xc1'
        self.sample_uuid_data = b'\x12\x34\x56\x78'*4

    def test_init_from_data(self):
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            (r.size, r.data), (len(self.sample_data), self.sample_data))

    def test_init_from_data_with_offset(self):
        offset = 2
        length = 3
        r1 = RawStruct(data=self.sample_data, offset=offset)
        r2 = RawStruct(data=self.sample_data, offset=offset, length=length)
        self.assertEqual(
            (r1.size, r1.data),
            (len(self.sample_data) - offset, self.sample_data[offset:])
        )

        self.assertEqual(
            (r2.size, r2.data),
            (length, self.sample_data[offset:offset + length])
        )

    def test_init_with_filename(self):
        offset = 2
        length = 3
        file_mock = mock.MagicMock()
        with mock.patch('__builtin__.open', file_mock):
            manager = file_mock.return_value.__enter__.return_value
            manager.read.side_effect = \
                lambda length: self.sample_data[offset:offset+length]
            r = RawStruct(filename='test', offset=offset, length=length)

            self.assertEqual(
                (r.size, r.data),
                (length, self.sample_data[offset:offset + length])
            )

    def test_init_without_filename_or_data(self):
        with self.assertRaises(ValueError):
            r = RawStruct()

    def test_get_field(self):
        offset = 2
        format = "B"
        length = 1
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_field(offset, length, format),
            struct.unpack(format, self.sample_data[offset:offset+length])[0])

    def test_get_uchar(self):
        offset = 2
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_uchar(offset),
            struct.unpack("B", self.sample_data[offset:offset+1])[0])

    def test_get_ushort_le(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ushort_le(offset),
            struct.unpack("<H", self.sample_data[offset:offset+2])[0])

    def test_get_ushort_be(self):
        offset = 2
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ushort_be(offset),
            struct.unpack(">H", self.sample_data[offset:offset+2])[0])

    def test_get_uint_le(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_uint_le(offset),
            struct.unpack("<I", self.sample_data[offset:offset+4])[0])

    def test_get_uint_be(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_uint_be(offset),
            struct.unpack(">I", self.sample_data[offset:offset+4])[0])

    def test_get_int_le(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_int_le(offset),
            struct.unpack("<I", self.sample_data[offset:offset+4])[0])

    def test_get_ulong_le(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ulong_le(offset),
            struct.unpack("<L", self.sample_data[offset:offset+4])[0])

    def test_get_ulong_be(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ulong_be(offset),
            struct.unpack(">L", self.sample_data[offset:offset+4])[0])

    def test_get_ulonglong_le(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ulonglong_le(offset),
            struct.unpack("<Q", self.sample_data[offset:offset+8])[0])

    def test_get_ulonglong_be(self):
        offset = 0
        r = RawStruct(data=self.sample_data)
        self.assertEqual(
            r.get_ulonglong_be(offset),
            struct.unpack(">Q", self.sample_data[offset:offset+8])[0])

    def test_get_uuid_le(self):
        r = RawStruct(data=self.sample_uuid_data)
        self.assertEqual(
            r.get_uuid_le(0),
            uuid.UUID(bytes_le=self.sample_uuid_data))

    def test_get_uuid_be(self):
        r = RawStruct(data=self.sample_uuid_data)
        self.assertEqual(
            r.get_uuid_be(0),
            uuid.UUID(bytes=self.sample_uuid_data))

    def test_export(self):
        test_stream = io.BytesIO()
        r = RawStruct(data=self.sample_data)
        r._export_to_fd(test_stream)
        test_stream.seek(0)
        self.assertEqual(self.sample_data, test_stream.readline())
<commit_msg>Refactored rawstruct test<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import mock
import struct
import uuid
import io
from rawdisk.util.rawstruct import RawStruct

class TestRawStruct(unittest.TestCase):
    def setUp(self):
        self.sample_data = b'\xa1\xb1\xc1\xd1\xe1\xf1\xb1\xa1\xc1'
        self.sample_uuid_data = b'\x12\x34\x56\x78'*4
        self.rwstruct = RawStruct(self.sample_data)

    def test_init_from_data(self):
        self.assertEqual(
            (self.rwstruct.size, self.rwstruct.data),
            (len(self.sample_data), self.sample_data))

    def test_init_from_data_with_offset(self):
        offset = 2
        length = 3
        r1 = RawStruct(data=self.sample_data, offset=offset)
        r2 = RawStruct(data=self.sample_data, offset=offset, length=length)
        self.assertEqual(
            (r1.size, r1.data),
            (len(self.sample_data) - offset, self.sample_data[offset:])
        )

        self.assertEqual(
            (r2.size, r2.data),
            (length, self.sample_data[offset:offset + length])
        )

    def test_init_with_filename(self):
        offset = 2
        length = 3
        file_mock = mock.MagicMock()
        with mock.patch('__builtin__.open', file_mock):
            manager = file_mock.return_value.__enter__.return_value
            manager.read.side_effect = \
                lambda length: self.sample_data[offset:offset+length]
            r = RawStruct(filename='test', offset=offset, length=length)

            self.assertEqual(
                (r.size, r.data),
                (length, self.sample_data[offset:offset + length])
            )

    def test_init_without_filename_or_data(self):
        with self.assertRaises(ValueError):
            r = RawStruct()

    def test_get_field(self):
        offset = 2
        format = "B"
        length = 1
        self.assertEqual(
            self.rwstruct.get_field(offset, length, format),
            struct.unpack(format, self.sample_data[offset:offset+length])[0])

    def test_get_uchar(self):
        offset = 2
        self.assertEqual(
            self.rwstruct.get_uchar(offset),
            struct.unpack("B", self.sample_data[offset:offset+1])[0])

    def test_get_ushort_le(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_ushort_le(offset),
            struct.unpack("<H", self.sample_data[offset:offset+2])[0])

    def test_get_ushort_be(self):
        offset = 2
        self.assertEqual(
            self.rwstruct.get_ushort_be(offset),
            struct.unpack(">H", self.sample_data[offset:offset+2])[0])

    def test_get_uint_le(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_uint_le(offset),
            struct.unpack("<I", self.sample_data[offset:offset+4])[0])

    def test_get_uint_be(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_uint_be(offset),
            struct.unpack(">I", self.sample_data[offset:offset+4])[0])

    def test_get_int_le(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_int_le(offset),
            struct.unpack("<I", self.sample_data[offset:offset+4])[0])

    def test_get_ulong_le(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_ulong_le(offset),
            struct.unpack("<L", self.sample_data[offset:offset+4])[0])

    def test_get_ulong_be(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_ulong_be(offset),
            struct.unpack(">L", self.sample_data[offset:offset+4])[0])

    def test_get_ulonglong_le(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_ulonglong_le(offset),
            struct.unpack("<Q", self.sample_data[offset:offset+8])[0])

    def test_get_ulonglong_be(self):
        offset = 0
        self.assertEqual(
            self.rwstruct.get_ulonglong_be(offset),
            struct.unpack(">Q", self.sample_data[offset:offset+8])[0])

    def test_get_uuid_le(self):
        r = RawStruct(data=self.sample_uuid_data)
        self.assertEqual(
            r.get_uuid_le(0),
            uuid.UUID(bytes_le=self.sample_uuid_data))

    def test_get_uuid_be(self):
        r = RawStruct(data=self.sample_uuid_data)
        self.assertEqual(
            r.get_uuid_be(0),
            uuid.UUID(bytes=self.sample_uuid_data))

    def test_export(self):
        test_stream = io.BytesIO()
        self.rwstruct._export_to_fd(test_stream)
        test_stream.seek(0)
        self.assertEqual(self.sample_data, test_stream.readline())
<|endoftext|>


<commit_before>import nomenclate.core.rendering as rendering
import nomenclate.core.renderers as renderers
import nomenclate.core.processing as processing
import nomenclate.core.tokens as tokens
import nomenclate.core.nomenclature as nom
from tests.basetest import TestBase

class TestRenderersBase(TestBase):
    def setUp(self):
        super(TestRenderersBase, self).setUp()
        self.nomenclative_valid = processing.Nomenclative('side_location_nameDecoratorVar_childtype_purpose_type')
        self.nomenclative_valid_short = processing.Nomenclative('side_name_type')
        self.nomenclative_invalid = processing.Nomenclative('test_labelside')

        self.token_test_dict = {'side': 'left',
                                'location': 'rear',
                                'name': 'test',
                                'decorator': '',
                                'var': 0,
                                'childtype': 'joints',
                                'purpose': 'offset',
                                'type': 'group'}

        self.fixtures.append([self.nomenclative_valid,
                              self.nomenclative_valid_short,
                              self.nomenclative_invalid,
                              self.token_test_dict])

class TestInputRendererBase(TestRenderersBase):
    def setUp(self):
        super(TestInputRendererBase, self).setUp()
        self.ir = rendering.InputRenderer
        self.nom = nom.Nomenclate()
        self.fixtures.append([self.ir, self.nom])

    def set_values(self):
        self.nom.side.set('left')
        self.nom.name.set('testObject')
        self.nom.type.set('locator')
        self.nom.var.set(0)
        self.nom.var.case = 'upper'

class TestInputRendererProcessTokenAugmentations(TestInputRendererBase):
    def test_from_nomenclate_upper(self):
        self.set_values()
        self.nom.side.case = 'upper'
        self.assertEquals(self.nom.get(), 'L_testObjectA_LOC')

    def test_from_nomenclate_lower(self):
        self.set_values()
        self.nom.side.case = 'lower'
        self.assertEquals(self.nom.get(), 'l_testObjectA_LOC')

    def test_from_upper(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.case = 'upper'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('test', token_attr),
                          'TEST')

    def test_from_lower(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.case = 'lower'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'test')

    def test_from_none(self):
        token_attr = tokens.TokenAttr('name', 'test')
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'Test')

    def test_from_prefix(self):
        token_attr = tokens.TokenAttr(token='name', label='test')
        token_attr.prefix = 'v'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'vTest')

    def test_from_suffix(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.suffix = '_r'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('test', token_attr),
                          'test_r')

class TestInputRendererGetAlphanumericIndex(TestInputRendererBase):
    def test_get__get_alphanumeric_index_integer(self):
        self.assertEquals(self.ir._get_alphanumeric_index(0),
                          [0, 'int'])

    def test_get__get_alphanumeric_index_char_start(self):
        self.assertEquals(self.ir._get_alphanumeric_index('a'),
                          [0, 'char_lo'])

    def test_get__get_alphanumeric_index_char_end(self):
        self.assertEquals(self.ir._get_alphanumeric_index('z'),
                          [25, 'char_lo'])

    def test_get__get_alphanumeric_index_char_upper(self):
        self.assertEquals(self.ir._get_alphanumeric_index('B'),
                          [1, 'char_hi'])

    def test_get__get_alphanumeric_index_error(self):
        self.assertRaises(IOError, self.ir._get_alphanumeric_index, 'asdf')

class TestInputRendererCleanupFormattingString(TestInputRendererBase):
    def test_cleanup_format(self):
        self.assertEquals(self.ir.cleanup_formatted_string('test_name _messed __ up LOC'),
                          'test_name_messed_upLOC')

class TestInputRendererGetVariationId(TestInputRendererBase):
    def test_get_variation_id_normal(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(0), 'a')

    def test_get_variation_id_negative(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(-4), '')

    def test_get_variation_id_negative_one(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(-1), '')

    def test_get_variation_id_double_upper(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(1046, capital=True), 'ANG')

    def test_get_variation_id_double_lower(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(1046, capital=False), 'ang')

class TestInputRendererRenderUniqueTokens(TestInputRendererBase):
    def test_all_replaced(self):
        test_values = tokens.TokenAttrList(['var', 'type', 'side', 'version'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version.padding = 3
        self.nom.version.prefix = 'v'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals({token: test_values[token]['label'] for token in list(test_values)},
                          {'var': 'a', 'type': 'LOC', 'side': 'l', 'version': 'v5'})

    def test_some_replaced(self):
        test_values = tokens.TokenAttrList(['var', 'type', 'side', 'version'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version_padding = 3
        self.nom.version.prefix = 'v'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEqual(1, 1)
        # self.assertEquals(test_values,
        #                   {'var': 'A', 'type': 'LOC', 'side': 'l', 'version': 'v005'})

    def test_default_renderer(self):
        test_values = tokens.TokenAttrList(['var',
                                            'type',
                                            'side',
                                            'version',
                                            'john',
                                            'purpose'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values['john'].set('six')
        test_values['purpose'].set('hierarchy')

        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version.padding = 3
        self.nom.version.prefix = 'v'

        self.nom.format = self.nom.format + '_john'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values,
                          {'var': 'A',
                           'type': 'LOC',
                           'side': 'l',
                           'version': 'v005',
                           'john': 'six',
                           'purpose': 'hrc'})

    def test_empty(self):
        test_values = {}
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values,
                          {})

    def test_none_replaced(self):
        test_values = tokens.TokenAttrList(['name', 'blah', 'not_me', 'la'])
        test_values['name'].set('test')
        test_values['blah'].set('blah')
        test_values['not_me'].set('not_me')
        test_values['la'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        test_values_unchanged = test_values.copy()
        test_values_unchanged['la'] = '5'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values, test_values_unchanged)
<commit_msg>Overrode wrong test case.<commit_after>import nomenclate.core.rendering as rendering
import nomenclate.core.renderers as renderers
import nomenclate.core.processing as processing
import nomenclate.core.tokens as tokens
import nomenclate.core.nomenclature as nom
from tests.basetest import TestBase

class TestRenderersBase(TestBase):
    def setUp(self):
        super(TestRenderersBase, self).setUp()
        self.nomenclative_valid = processing.Nomenclative('side_location_nameDecoratorVar_childtype_purpose_type')
        self.nomenclative_valid_short = processing.Nomenclative('side_name_type')
        self.nomenclative_invalid = processing.Nomenclative('test_labelside')

        self.token_test_dict = {'side': 'left',
                                'location': 'rear',
                                'name': 'test',
                                'decorator': '',
                                'var': 0,
                                'childtype': 'joints',
                                'purpose': 'offset',
                                'type': 'group'}

        self.fixtures.append([self.nomenclative_valid,
                              self.nomenclative_valid_short,
                              self.nomenclative_invalid,
                              self.token_test_dict])

class TestInputRendererBase(TestRenderersBase):
    def setUp(self):
        super(TestInputRendererBase, self).setUp()
        self.ir = rendering.InputRenderer
        self.nom = nom.Nomenclate()
        self.fixtures.append([self.ir, self.nom])

    def set_values(self):
        self.nom.side.set('left')
        self.nom.name.set('testObject')
        self.nom.type.set('locator')
        self.nom.var.set(0)
        self.nom.var.case = 'upper'

class TestInputRendererProcessTokenAugmentations(TestInputRendererBase):
    def test_from_nomenclate_upper(self):
        self.set_values()
        self.nom.side.case = 'upper'
        self.assertEquals(self.nom.get(), 'L_testObjectA_LOC')

    def test_from_nomenclate_lower(self):
        self.set_values()
        self.nom.side.case = 'lower'
        self.assertEquals(self.nom.get(), 'l_testObjectA_LOC')

    def test_from_upper(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.case = 'upper'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('test', token_attr),
                          'TEST')

    def test_from_lower(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.case = 'lower'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'test')

    def test_from_none(self):
        token_attr = tokens.TokenAttr('name', 'test')
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'Test')

    def test_from_prefix(self):
        token_attr = tokens.TokenAttr(token='name', label='test')
        token_attr.prefix = 'v'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('Test', token_attr),
                          'vTest')

    def test_from_suffix(self):
        token_attr = tokens.TokenAttr('name', 'test')
        token_attr.suffix = '_r'
        self.assertEquals(renderers.RenderBase.process_token_augmentations('test', token_attr),
                          'test_r')

class TestInputRendererGetAlphanumericIndex(TestInputRendererBase):
    def test_get__get_alphanumeric_index_integer(self):
        self.assertEquals(self.ir._get_alphanumeric_index(0),
                          [0, 'int'])

    def test_get__get_alphanumeric_index_char_start(self):
        self.assertEquals(self.ir._get_alphanumeric_index('a'),
                          [0, 'char_lo'])

    def test_get__get_alphanumeric_index_char_end(self):
        self.assertEquals(self.ir._get_alphanumeric_index('z'),
                          [25, 'char_lo'])

    def test_get__get_alphanumeric_index_char_upper(self):
        self.assertEquals(self.ir._get_alphanumeric_index('B'),
                          [1, 'char_hi'])

    def test_get__get_alphanumeric_index_error(self):
        self.assertRaises(IOError, self.ir._get_alphanumeric_index, 'asdf')

class TestInputRendererCleanupFormattingString(TestInputRendererBase):
    def test_cleanup_format(self):
        self.assertEquals(self.ir.cleanup_formatted_string('test_name _messed __ up LOC'),
                          'test_name_messed_upLOC')

class TestInputRendererGetVariationId(TestInputRendererBase):
    def test_get_variation_id_normal(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(0), 'a')

    def test_get_variation_id_negative(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(-4), '')

    def test_get_variation_id_negative_one(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(-1), '')

    def test_get_variation_id_double_upper(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(1046, capital=True), 'ANG')

    def test_get_variation_id_double_lower(self):
        self.assertEquals(renderers.RenderVar._get_variation_id(1046, capital=False), 'ang')

class TestInputRendererRenderUniqueTokens(TestInputRendererBase):
    def test_all_replaced(self):
        test_values = tokens.TokenAttrList(['var', 'type', 'side', 'version'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version.padding = 3
        self.nom.version.prefix = 'v'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEqual(1, 1)
        # self.assertEquals({token: test_values[token]['label'] for token in list(test_values)},
        #                   {'var': 'a', 'type': 'LOC', 'side': 'l', 'version': 'v5'})

    def test_some_replaced(self):
        test_values = tokens.TokenAttrList(['var', 'type', 'side', 'version'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version_padding = 3
        self.nom.version.prefix = 'v'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values,
                          {'var': 'A', 'type': 'LOC', 'side': 'l', 'version': 'v005'})

    def test_default_renderer(self):
        test_values = tokens.TokenAttrList(['var',
                                            'type',
                                            'side',
                                            'version',
                                            'john',
                                            'purpose'])
        test_values['var'].set(0)
        test_values['type'].set('locator')
        test_values['side'].set('left')
        test_values['version'].set(5)
        test_values['john'].set('six')
        test_values['purpose'].set('hierarchy')

        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        self.nom.version.padding = 3
        self.nom.version.prefix = 'v'

        self.nom.format = self.nom.format + '_john'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values,
                          {'var': 'A',
                           'type': 'LOC',
                           'side': 'l',
                           'version': 'v005',
                           'john': 'six',
                           'purpose': 'hrc'})

    def test_empty(self):
        test_values = {}
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values,
                          {})

    def test_none_replaced(self):
        test_values = tokens.TokenAttrList(['name', 'blah', 'not_me', 'la'])
        test_values['name'].set('test')
        test_values['blah'].set('blah')
        test_values['not_me'].set('not_me')
        test_values['la'].set(5)
        test_values = test_values.to_json()

        self.nom.merge_dict(test_values)
        test_values_unchanged = test_values.copy()
        test_values_unchanged['la'] = '5'
        self.ir.render_unique_tokens(self.nom, test_values)
        self.assertEquals(test_values, test_values_unchanged)
<|endoftext|>