<commit_before>import unittest
from abc import ABC, abstractmethod
from provdbconnector.databases.baseconnector import BaseConnector
from prov.tests.examples import primer_example
from prov.model import ProvRecord, ProvDocument

from tests.examples import base_connector_record_parameter_example,base_connector_relation_parameter_example
class ConnectorTestTemplate(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        """
        Prevent from execute the test case directly see:

        http://stackoverflow.com/questions/4566910/abstract-test-case-using-python-unittest

        :param args:
        :param kwargs:
        """
        super(ConnectorTestTemplate, self).__init__(*args, **kwargs)
        self.helper = None
        # Kludge alert: We want this class to carry test cases without being run
        # by the unit test framework, so the `run' method is overridden to do
        # nothing.  But in order for sub-classes to be able to do something when
        # run is invoked, the constructor will rebind `run' from TestCase.
        if self.__class__ != ConnectorTestTemplate:
            # Rebind `run' from the parent class.
            self.run = unittest.TestCase.run.__get__(self, self.__class__)
        else:
            self.run = lambda self, *args, **kwargs: None

    ### create section ###
    def test_create_document(self):
        id = self.instance.create_document()
        self.assertIsNotNone(id)
        self.assertIs(type(id), str,"id should be a string ")

    def test_create_bundle(self):
        doc_id = self.instance.create_document()
        id = self.instance.create_bundle(doc_id)
        self.assertIsNotNone(id)
        self.assertIs(type(id), str, "id should be a string ")

    def test_create_record(self):
        args = base_connector_record_parameter_example()

        doc_id = self.instance.create_document()
        record_id  = self.instance.create_record(doc_id, args.attributes, args.metadata)
        self.assertIsNotNone(record_id)
        self.assertIs(type(record_id), str, "id should be a string ")

    def test_create_relation(self):
        args = base_connector_relation_parameter_example()

        doc_id = self.instance.create_document()
        record_id = self.instance.create_relation(doc_id, args.attributes, args.metadata)
        self.assertIsNotNone(record_id)
        self.assertIs(type(record_id), str, "id should be a string ")

    ### Get section ###
    def test_get_document(self):
        args = base_connector_record_parameter_example()

        doc_id = self.instance.create_document()
        record_id = self.instance.create_record(doc_id, args.attributes, args.metadata)

        prov_doc = self.instance.get_document(doc_id)

        self.assertIsNotNone(prov_doc)
        self.assertIsInstance(prov_doc,ProvDocument)
        self.assertEqual(prov_doc.get_records(), 1)

        prov_record = prov_doc.get_records().pop()
        self.assertIsInstance(prov_record,ProvRecord)
        self.assertEqual(prov_record, args.prov_record)

    def test_get_bundle(self):
        NotImplementedError()

    def test_get_record(self):
        NotImplementedError()

    def test_get_relation(self):
        NotImplementedError()

    ###Delete section ###
    def test_delete_document(self):
        NotImplementedError()

    def test_delete_bundle(self):
        NotImplementedError()

    def test_delete_record(self):
        NotImplementedError()

    def test_delete_relation(self):
        NotImplementedError()

class BaseConnectorTests(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_instance_abstract_class(self):

        with self.assertRaises(TypeError):
            instance = BaseConnector()

<commit_msg>- add raise command<commit_after>import unittest
from abc import ABC, abstractmethod
from provdbconnector.databases.baseconnector import BaseConnector
from prov.tests.examples import primer_example
from prov.model import ProvRecord, ProvDocument

from tests.examples import base_connector_record_parameter_example,base_connector_relation_parameter_example
class ConnectorTestTemplate(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        """
        Prevent from execute the test case directly see:

        http://stackoverflow.com/questions/4566910/abstract-test-case-using-python-unittest

        :param args:
        :param kwargs:
        """
        super(ConnectorTestTemplate, self).__init__(*args, **kwargs)
        self.helper = None
        # Kludge alert: We want this class to carry test cases without being run
        # by the unit test framework, so the `run' method is overridden to do
        # nothing.  But in order for sub-classes to be able to do something when
        # run is invoked, the constructor will rebind `run' from TestCase.
        if self.__class__ != ConnectorTestTemplate:
            # Rebind `run' from the parent class.
            self.run = unittest.TestCase.run.__get__(self, self.__class__)
        else:
            self.run = lambda self, *args, **kwargs: None

    ### create section ###
    def test_create_document(self):
        id = self.instance.create_document()
        self.assertIsNotNone(id)
        self.assertIs(type(id), str,"id should be a string ")

    def test_create_bundle(self):
        doc_id = self.instance.create_document()
        id = self.instance.create_bundle(doc_id)
        self.assertIsNotNone(id)
        self.assertIs(type(id), str, "id should be a string ")

    def test_create_record(self):
        args = base_connector_record_parameter_example()

        doc_id = self.instance.create_document()
        record_id  = self.instance.create_record(doc_id, args.attributes, args.metadata)
        self.assertIsNotNone(record_id)
        self.assertIs(type(record_id), str, "id should be a string ")

    def test_create_relation(self):
        args = base_connector_relation_parameter_example()

        doc_id = self.instance.create_document()
        record_id = self.instance.create_relation(doc_id, args.attributes, args.metadata)
        self.assertIsNotNone(record_id)
        self.assertIs(type(record_id), str, "id should be a string ")

    ### Get section ###
    def test_get_document(self):
        args = base_connector_record_parameter_example()

        doc_id = self.instance.create_document()
        record_id = self.instance.create_record(doc_id, args.attributes, args.metadata)

        prov_doc = self.instance.get_document(doc_id)

        self.assertIsNotNone(prov_doc)
        self.assertIsInstance(prov_doc,ProvDocument)
        self.assertEqual(prov_doc.get_records(), 1)

        prov_record = prov_doc.get_records().pop()
        self.assertIsInstance(prov_record,ProvRecord)
        self.assertEqual(prov_record, args.prov_record)

    def test_get_bundle(self):
        raise NotImplementedError()

    def test_get_record(self):
        raise NotImplementedError()

    def test_get_relation(self):
        raise NotImplementedError()

    ###Delete section ###
    def test_delete_document(self):
        raise NotImplementedError()

    def test_delete_bundle(self):
        raise NotImplementedError()

    def test_delete_record(self):
        raise NotImplementedError()

    def test_delete_relation(self):
        raise NotImplementedError()

class BaseConnectorTests(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_instance_abstract_class(self):

        with self.assertRaises(TypeError):
            instance = BaseConnector()

<|endoftext|>


<commit_before>from datetime import datetime, timedelta
from inbox.models import Event, Account

ACCOUNT_ID = 1
NAMESPACE_ID = 1
START = datetime.utcnow()
END = START + timedelta(0, 1)

def default_calendar(db_session):
    account = db_session.query(Account).filter(
        Account.id == ACCOUNT_ID).one()
    return account.default_calendar

def default_event(db_session):
    cal = default_calendar(db_session)
    ev = Event(namespace_id=NAMESPACE_ID,
               calendar=cal,
               title='title',
               description='',
               location='',
               busy=False,
               read_only=False,
               reminders='',
               recurrence='',
               start=START,
               end=END,
               all_day=False,
               provider_name='inbox',
               raw_data='',
               source='remote')

    db_session.add(ev)
    db_session.commit()
    return ev
<commit_msg>make default test event local, since remote ones suppress transactions<commit_after>from datetime import datetime, timedelta
from inbox.models import Event, Account

ACCOUNT_ID = 1
NAMESPACE_ID = 1
START = datetime.utcnow()
END = START + timedelta(0, 1)

def default_calendar(db_session):
    account = db_session.query(Account).filter(
        Account.id == ACCOUNT_ID).one()
    return account.default_calendar

def default_event(db_session):
    cal = default_calendar(db_session)
    ev = Event(namespace_id=NAMESPACE_ID,
               calendar=cal,
               title='title',
               description='',
               location='',
               busy=False,
               read_only=False,
               reminders='',
               recurrence='',
               start=START,
               end=END,
               all_day=False,
               provider_name='inbox',
               raw_data='',
               source='local')

    db_session.add(ev)
    db_session.commit()
    return ev
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
Tests man spm
'''
# Import python libs
from __future__ import absolute_import

# Import Salt Testing libs
from tests.support.case import ModuleCase

class SPMManTest(ModuleCase):
    '''
    Validate man spm
    '''
    def test_man_spm(self):
        '''
        test man spm
        '''
        cmd = self.run_function('cmd.run', ['man spm'])
        self.assertIn('Salt Package Manager', cmd)
        self.assertIn('spm is the frontend command for managing Salt packages.', cmd)
<commit_msg>fix_string_error<commit_after># -*- coding: utf-8 -*-
'''
Tests man spm
'''
# Import python libs
from __future__ import absolute_import

# Import Salt Testing libs
from tests.support.case import ModuleCase

class SPMManTest(ModuleCase):
    '''
    Validate man spm
    '''
    def test_man_spm(self):
        '''
        test man spm
        '''
        cmd = self.run_function('cmd.run', ['man spm'])
        self.assertIn('Salt Package Manager', cmd)
        self.assertIn('command for managing Salt packages', cmd)
<|endoftext|>


<commit_before>import asyncio

import pytest

from .. import base

MB = 1

@base.bootstrapped
@pytest.mark.asyncio
async def test_action(event_loop):
    async with base.CleanModel() as model:
        ubuntu_app = await model.deploy(
            'percona-cluster',
            application_name='mysql',
            series='xenial',
            channel='stable',
            config={
                'tuning-level': 'safest',
            },
            constraints={
                'mem': 256 * MB,
            },
        )

        # update and check app config
        await ubuntu_app.set_config({'tuning-level': 'fast'})
        config = await ubuntu_app.get_config()
        assert config['tuning-level']['value'] == 'fast'

        # Restore config back to default
        await ubuntu_app.reset_config(['tuning-level'])
        config = await ubuntu_app.get_config()
        assert config['tuning-level']['value'] == 'safest'

        # update and check app constraints
        await ubuntu_app.set_constraints({'mem': 512 * MB})
        constraints = await ubuntu_app.get_constraints()
        assert constraints['mem'] == 512 * MB

        # check action definitions
        actions = await ubuntu_app.get_actions()
        assert 'backup' in actions.keys()

@base.bootstrapped
@pytest.mark.asyncio
async def test_add_units(event_loop):
    from juju.unit import Unit

    async with base.CleanModel() as model:
        app = await model.deploy(
            'ubuntu-0',
            application_name='ubuntu',
            series='trusty',
            channel='stable',
        )
        units = await app.add_units(count=2)

        assert len(units) == 2
        for unit in units:
            assert isinstance(unit, Unit)

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: len(app.units) > 0)
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm()
        assert app.data['charm-url'].startswith('cs:ubuntu-')
        assert app.data['charm-url'] != 'cs:ubuntu-0'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_channel(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: len(app.units) > 0)
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(channel='stable')
        assert app.data['charm-url'].startswith('cs:ubuntu-')
        assert app.data['charm-url'] != 'cs:ubuntu-0'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_revision(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: len(app.units) > 0)
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(revision=8)
        assert app.data['charm-url'] == 'cs:ubuntu-8'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_switch(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: len(app.units) > 0)
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(switch='ubuntu-8')
        assert app.data['charm-url'] == 'cs:ubuntu-8'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_resource(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('cs:~cynerva/upgrade-charm-resource-test-1')

        def units_ready():
            if not app.units:
                return False
            unit = app.units[0]
            return unit.workload_status == 'active' and \
                unit.agent_status == 'idle'

        await asyncio.wait_for(model.block_until(units_ready), timeout=480)
        unit = app.units[0]
        expected_message = 'I have no resource.'
        assert unit.workload_status_message == expected_message

        await app.upgrade_charm(revision=2)
        await asyncio.wait_for(
            model.block_until(
                lambda: unit.workload_status_message != 'I have no resource.'
            ),
            timeout=60
        )
        expected_message = 'My resource: I am the resource.'
        assert app.units[0].workload_status_message == expected_message
<commit_msg>Fix the fix for the upgrade charm tests (#298)<commit_after>import asyncio

import pytest

from .. import base

MB = 1

@base.bootstrapped
@pytest.mark.asyncio
async def test_action(event_loop):
    async with base.CleanModel() as model:
        ubuntu_app = await model.deploy(
            'percona-cluster',
            application_name='mysql',
            series='xenial',
            channel='stable',
            config={
                'tuning-level': 'safest',
            },
            constraints={
                'mem': 256 * MB,
            },
        )

        # update and check app config
        await ubuntu_app.set_config({'tuning-level': 'fast'})
        config = await ubuntu_app.get_config()
        assert config['tuning-level']['value'] == 'fast'

        # Restore config back to default
        await ubuntu_app.reset_config(['tuning-level'])
        config = await ubuntu_app.get_config()
        assert config['tuning-level']['value'] == 'safest'

        # update and check app constraints
        await ubuntu_app.set_constraints({'mem': 512 * MB})
        constraints = await ubuntu_app.get_constraints()
        assert constraints['mem'] == 512 * MB

        # check action definitions
        actions = await ubuntu_app.get_actions()
        assert 'backup' in actions.keys()

@base.bootstrapped
@pytest.mark.asyncio
async def test_add_units(event_loop):
    from juju.unit import Unit

    async with base.CleanModel() as model:
        app = await model.deploy(
            'ubuntu-0',
            application_name='ubuntu',
            series='trusty',
            channel='stable',
        )
        units = await app.add_units(count=2)

        assert len(units) == 2
        for unit in units:
            assert isinstance(unit, Unit)

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: (len(app.units) > 0 and
                                         app.units[0].machine))
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm()
        assert app.data['charm-url'].startswith('cs:ubuntu-')
        assert app.data['charm-url'] != 'cs:ubuntu-0'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_channel(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: (len(app.units) > 0 and
                                         app.units[0].machine))
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(channel='stable')
        assert app.data['charm-url'].startswith('cs:ubuntu-')
        assert app.data['charm-url'] != 'cs:ubuntu-0'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_revision(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: (len(app.units) > 0 and
                                         app.units[0].machine))
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(revision=8)
        assert app.data['charm-url'] == 'cs:ubuntu-8'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_switch(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('ubuntu-0')
        await model.block_until(lambda: (len(app.units) > 0 and
                                         app.units[0].machine))
        assert app.data['charm-url'] == 'cs:ubuntu-0'
        await app.upgrade_charm(switch='ubuntu-8')
        assert app.data['charm-url'] == 'cs:ubuntu-8'

@base.bootstrapped
@pytest.mark.asyncio
async def test_upgrade_charm_resource(event_loop):
    async with base.CleanModel() as model:
        app = await model.deploy('cs:~cynerva/upgrade-charm-resource-test-1')

        def units_ready():
            if not app.units:
                return False
            unit = app.units[0]
            return unit.workload_status == 'active' and \
                unit.agent_status == 'idle'

        await asyncio.wait_for(model.block_until(units_ready), timeout=480)
        unit = app.units[0]
        expected_message = 'I have no resource.'
        assert unit.workload_status_message == expected_message

        await app.upgrade_charm(revision=2)
        await asyncio.wait_for(
            model.block_until(
                lambda: unit.workload_status_message != 'I have no resource.'
            ),
            timeout=60
        )
        expected_message = 'My resource: I am the resource.'
        assert app.units[0].workload_status_message == expected_message
<|endoftext|>


<commit_before>"""
Tests for the mock of the get duplicates endpoint.
"""

import base64
import io
import uuid

import pytest
from requests import codes
from requests_mock import GET

from mock_vws._constants import ResultCodes
from tests.mock_vws.utils import (
    add_target_to_vws,
    get_vws_target,
    target_api_request,
    wait_for_target_processed,
)
from tests.mock_vws.utils.assertions import assert_vws_response
from tests.mock_vws.utils.authorization import VuforiaDatabaseKeys

@pytest.mark.usefixtures('verify_mock_vuforia')
class TestDuplicates:
    """
    Tests for the mock of the target duplicates endpoint.
    """

    def test_duplicates(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
        png_rgb_success: io.BytesIO,
    ) -> None:
        """
        Target IDs of similar targets are returned.

        In the mock, "similar" means that the images are exactly the same.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        different = png_rgb_success.read()
        different_data_encoded = base64.b64encode(different).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        different_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': different_data_encoded,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        different_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=different_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']
        different_target_id = different_add_resp.json()['target_id']

        for target_id in {
            original_target_id,
            similar_target_id,
            different_target_id,
        }:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert_vws_response(
            response=response,
            status_code=codes.OK,
            result_code=ResultCodes.SUCCESS,
        )

        expected_keys = {
            'result_code',
            'transaction_id',
            'similar_targets',
        }

        assert response.json().keys() == expected_keys

        assert response.json()['similar_targets'] == [similar_target_id]

    def test_status(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        png_greyscale: io.BytesIO,
    ) -> None:
        """
        Targets are not duplicates if the status is not 'success'.
        """
        image_data = png_greyscale.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = get_vws_target(
            vuforia_database_keys=vuforia_database_keys,
            target_id=original_target_id,
        )

        assert response.json()['status'] == 'failed'

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == []

    def test_active_flag_duplicate(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
    ) -> None:
        """
        Targets with `active_flag` set to `False` are not found as duplicates.

        https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API#How-To-Check-for-Duplicate-Targets
    says:

        > If a target is explicitly inactivated through the VWS API (or through
        > the Target Manager), then this target is no longer taken into account
        > for the duplicate target check.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': True,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': False,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == []

    def test_active_flag_original(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
    ) -> None:
        """
        Targets with `active_flag` set to `False` can have duplicates.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': False,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': True,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == [similar_target_id]
<commit_msg>Stubs for new tests<commit_after>"""
Tests for the mock of the get duplicates endpoint.
"""

import base64
import io
import uuid

import pytest
from requests import codes
from requests_mock import GET

from mock_vws._constants import ResultCodes
from tests.mock_vws.utils import (
    add_target_to_vws,
    get_vws_target,
    target_api_request,
    wait_for_target_processed,
)
from tests.mock_vws.utils.assertions import assert_vws_response
from tests.mock_vws.utils.authorization import VuforiaDatabaseKeys

@pytest.mark.usefixtures('verify_mock_vuforia')
class TestDuplicates:
    """
    Tests for the mock of the target duplicates endpoint.
    """

    def test_duplicates(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
        png_rgb_success: io.BytesIO,
    ) -> None:
        """
        Target IDs of similar targets are returned.

        In the mock, "similar" means that the images are exactly the same.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        different = png_rgb_success.read()
        different_data_encoded = base64.b64encode(different).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        different_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': different_data_encoded,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        different_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=different_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']
        different_target_id = different_add_resp.json()['target_id']

        for target_id in {
            original_target_id,
            similar_target_id,
            different_target_id,
        }:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert_vws_response(
            response=response,
            status_code=codes.OK,
            result_code=ResultCodes.SUCCESS,
        )

        expected_keys = {
            'result_code',
            'transaction_id',
            'similar_targets',
        }

        assert response.json().keys() == expected_keys

        assert response.json()['similar_targets'] == [similar_target_id]

    def test_status(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        png_greyscale: io.BytesIO,
    ) -> None:
        """
        Targets are not duplicates if the status is not 'success'.
        """
        image_data = png_greyscale.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = get_vws_target(
            vuforia_database_keys=vuforia_database_keys,
            target_id=original_target_id,
        )

        assert response.json()['status'] == 'failed'

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == []

    def test_active_flag_duplicate(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
    ) -> None:
        """
        Targets with `active_flag` set to `False` are not found as duplicates.

        https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API#How-To-Check-for-Duplicate-Targets
    says:

        > If a target is explicitly inactivated through the VWS API (or through
        > the Target Manager), then this target is no longer taken into account
        > for the duplicate target check.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': True,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': False,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == []

    def test_active_flag_original(
        self,
        vuforia_database_keys: VuforiaDatabaseKeys,
        high_quality_image: io.BytesIO,
    ) -> None:
        """
        Targets with `active_flag` set to `False` can have duplicates.
        """
        image_data = high_quality_image.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        original_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': False,
        }

        similar_data = {
            'name': str(uuid.uuid4()),
            'width': 1,
            'image': image_data_encoded,
            'active_flag': True,
        }

        original_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=original_data,
        )

        similar_add_resp = add_target_to_vws(
            vuforia_database_keys=vuforia_database_keys,
            data=similar_data,
        )

        original_target_id = original_add_resp.json()['target_id']
        similar_target_id = similar_add_resp.json()['target_id']

        for target_id in {original_target_id, similar_target_id}:
            wait_for_target_processed(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

        response = target_api_request(
            server_access_key=vuforia_database_keys.server_access_key,
            server_secret_key=vuforia_database_keys.server_secret_key,
            method=GET,
            content=b'',
            request_path='/duplicates/' + original_target_id,
        )

        assert response.json()['similar_targets'] == [similar_target_id]

@pytest.mark.usefixtures('verify_mock_vuforia')
class TestProcessing:
    """
    Tests for targets in the processing stage.
    """

    def test_original_processing(self) -> None:
        """
        Checking for duplicates on a target which is processing, ...
        """
        pass

    def test_duplicate_processing(self) -> None:
        """
        Checking for duplicates on a target which is processed, when another
        target which is a duplicate is processing, ...
        """
        pass
<|endoftext|>


<commit_before>"""
30. Object pagination

Django provides a framework for paginating a list of objects in a few lines
of code. This is often useful for dividing search results or long lists of
objects into easily readable pages.

In Django 0.96 and earlier, a single ObjectPaginator class implemented this
functionality. In the Django development version, the behavior is split across
two classes -- Paginator and Page -- that are more easier to use. The legacy
ObjectPaginator class is deprecated.
"""

from django.db import models

class Article(models.Model):
    headline = models.CharField(max_length=100, default='Default headline')
    pub_date = models.DateTimeField()

    def __unicode__(self):
        return self.headline

__test__ = {'API_TESTS':"""
# Prepare a list of objects for pagination.
>>> from datetime import datetime
>>> for x in range(1, 10):
...     a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29))
...     a.save()

####################################
# New/current API (Paginator/Page) #
####################################

>>> from django.core.paginator import Paginator, InvalidPage
>>> paginator = Paginator(Article.objects.all(), 5)
>>> paginator.count
9
>>> paginator.num_pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> p = paginator.page(1)
>>> p
<Page 1 of 2>
>>> p.object_list
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>, <Article: Article 5>]
>>> p.has_next()
True
>>> p.has_previous()
False
>>> p.has_other_pages()
True
>>> p.next_page_number()
2
>>> p.previous_page_number()
0
>>> p.start_index()
1
>>> p.end_index()
5

# Get the second page.
>>> p = paginator.page(2)
>>> p
<Page 2 of 2>
>>> p.object_list
[<Article: Article 6>, <Article: Article 7>, <Article: Article 8>, <Article: Article 9>]
>>> p.has_next()
False
>>> p.has_previous()
True
>>> p.has_other_pages()
True
>>> p.next_page_number()
3
>>> p.previous_page_number()
1
>>> p.start_index()
6
>>> p.end_index()
9

# Invalid pages raise InvalidPage.
>>> paginator.page(0)
Traceback (most recent call last):
...
InvalidPage: ...
>>> paginator.page(3)
Traceback (most recent call last):
...
InvalidPage: ...

# Empty paginators with allow_empty_first_page=True.
>>> paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=True)
>>> paginator.count
0
>>> paginator.num_pages
1
>>> paginator.page_range
[1]

# Empty paginators with allow_empty_first_page=False.
>>> paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=False)
>>> paginator.count
0
>>> paginator.num_pages
0
>>> paginator.page_range
[]

# Paginators work with regular lists/tuples, too -- not just with QuerySets.
>>> paginator = Paginator([1, 2, 3, 4, 5, 6, 7, 8, 9], 5)
>>> paginator.count
9
>>> paginator.num_pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> p = paginator.page(1)
>>> p
<Page 1 of 2>
>>> p.object_list
[1, 2, 3, 4, 5]
>>> p.has_next()
True
>>> p.has_previous()
False
>>> p.has_other_pages()
True
>>> p.next_page_number()
2
>>> p.previous_page_number()
0
>>> p.start_index()
1
>>> p.end_index()
5

################################
# Legacy API (ObjectPaginator) #
################################

>>> from django.core.paginator import ObjectPaginator, InvalidPage
>>> paginator = ObjectPaginator(Article.objects.all(), 5)
>>> paginator.hits
9
>>> paginator.pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> paginator.get_page(0)
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>, <Article: Article 5>]
>>> paginator.has_next_page(0)
True
>>> paginator.has_previous_page(0)
False
>>> paginator.first_on_page(0)
1
>>> paginator.last_on_page(0)
5

# Get the second page.
>>> paginator.get_page(1)
[<Article: Article 6>, <Article: Article 7>, <Article: Article 8>, <Article: Article 9>]
>>> paginator.has_next_page(1)
False
>>> paginator.has_previous_page(1)
True
>>> paginator.first_on_page(1)
6
>>> paginator.last_on_page(1)
9

# Invalid pages raise InvalidPage.
>>> paginator.get_page(-1)
Traceback (most recent call last):
...
InvalidPage: ...
>>> paginator.get_page(2)
Traceback (most recent call last):
...
InvalidPage: ...

# Empty paginators with allow_empty_first_page=True.
>>> paginator = ObjectPaginator(Article.objects.filter(id=0), 5)
>>> paginator.count
0
>>> paginator.num_pages
1
>>> paginator.page_range
[1]

##################
# Orphan support #
##################

# Add a few more records to test out the orphans feature.
>>> for x in range(10, 13):
...     Article(headline="Article %s" % x, pub_date=datetime(2006, 10, 6)).save()

# With orphans set to 3 and 10 items per page, we should get all 12 items on a single page.
>>> paginator = Paginator(Article.objects.all(), 10, orphans=3)
>>> paginator.num_pages
1

# With orphans only set to 1, we should get two pages.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=1)
>>> paginator.num_pages
2

# LEGACY: With orphans set to 3 and 10 items per page, we should get all 12 items on a single page.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=3)
>>> paginator.pages
1

# LEGACY: With orphans only set to 1, we should get two pages.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=1)
>>> paginator.pages
2
"""}
<commit_msg>Changed pagination tests to suppress the DeprecationWarning<commit_after>"""
30. Object pagination

Django provides a framework for paginating a list of objects in a few lines
of code. This is often useful for dividing search results or long lists of
objects into easily readable pages.

In Django 0.96 and earlier, a single ObjectPaginator class implemented this
functionality. In the Django development version, the behavior is split across
two classes -- Paginator and Page -- that are more easier to use. The legacy
ObjectPaginator class is deprecated.
"""

from django.db import models

class Article(models.Model):
    headline = models.CharField(max_length=100, default='Default headline')
    pub_date = models.DateTimeField()

    def __unicode__(self):
        return self.headline

__test__ = {'API_TESTS':"""
# Prepare a list of objects for pagination.
>>> from datetime import datetime
>>> for x in range(1, 10):
...     a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29))
...     a.save()

####################################
# New/current API (Paginator/Page) #
####################################

>>> from django.core.paginator import Paginator, InvalidPage
>>> paginator = Paginator(Article.objects.all(), 5)
>>> paginator.count
9
>>> paginator.num_pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> p = paginator.page(1)
>>> p
<Page 1 of 2>
>>> p.object_list
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>, <Article: Article 5>]
>>> p.has_next()
True
>>> p.has_previous()
False
>>> p.has_other_pages()
True
>>> p.next_page_number()
2
>>> p.previous_page_number()
0
>>> p.start_index()
1
>>> p.end_index()
5

# Get the second page.
>>> p = paginator.page(2)
>>> p
<Page 2 of 2>
>>> p.object_list
[<Article: Article 6>, <Article: Article 7>, <Article: Article 8>, <Article: Article 9>]
>>> p.has_next()
False
>>> p.has_previous()
True
>>> p.has_other_pages()
True
>>> p.next_page_number()
3
>>> p.previous_page_number()
1
>>> p.start_index()
6
>>> p.end_index()
9

# Invalid pages raise InvalidPage.
>>> paginator.page(0)
Traceback (most recent call last):
...
InvalidPage: ...
>>> paginator.page(3)
Traceback (most recent call last):
...
InvalidPage: ...

# Empty paginators with allow_empty_first_page=True.
>>> paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=True)
>>> paginator.count
0
>>> paginator.num_pages
1
>>> paginator.page_range
[1]

# Empty paginators with allow_empty_first_page=False.
>>> paginator = Paginator(Article.objects.filter(id=0), 5, allow_empty_first_page=False)
>>> paginator.count
0
>>> paginator.num_pages
0
>>> paginator.page_range
[]

# Paginators work with regular lists/tuples, too -- not just with QuerySets.
>>> paginator = Paginator([1, 2, 3, 4, 5, 6, 7, 8, 9], 5)
>>> paginator.count
9
>>> paginator.num_pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> p = paginator.page(1)
>>> p
<Page 1 of 2>
>>> p.object_list
[1, 2, 3, 4, 5]
>>> p.has_next()
True
>>> p.has_previous()
False
>>> p.has_other_pages()
True
>>> p.next_page_number()
2
>>> p.previous_page_number()
0
>>> p.start_index()
1
>>> p.end_index()
5

################################
# Legacy API (ObjectPaginator) #
################################

# Don't print out the deprecation warnings during testing.
>>> from warnings import filterwarnings
>>> filterwarnings("ignore")

>>> from django.core.paginator import ObjectPaginator, InvalidPage
>>> paginator = ObjectPaginator(Article.objects.all(), 5)
>>> paginator.hits
9
>>> paginator.pages
2
>>> paginator.page_range
[1, 2]

# Get the first page.
>>> paginator.get_page(0)
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>, <Article: Article 5>]
>>> paginator.has_next_page(0)
True
>>> paginator.has_previous_page(0)
False
>>> paginator.first_on_page(0)
1
>>> paginator.last_on_page(0)
5

# Get the second page.
>>> paginator.get_page(1)
[<Article: Article 6>, <Article: Article 7>, <Article: Article 8>, <Article: Article 9>]
>>> paginator.has_next_page(1)
False
>>> paginator.has_previous_page(1)
True
>>> paginator.first_on_page(1)
6
>>> paginator.last_on_page(1)
9

# Invalid pages raise InvalidPage.
>>> paginator.get_page(-1)
Traceback (most recent call last):
...
InvalidPage: ...
>>> paginator.get_page(2)
Traceback (most recent call last):
...
InvalidPage: ...

# Empty paginators with allow_empty_first_page=True.
>>> paginator = ObjectPaginator(Article.objects.filter(id=0), 5)
>>> paginator.count
0
>>> paginator.num_pages
1
>>> paginator.page_range
[1]

##################
# Orphan support #
##################

# Add a few more records to test out the orphans feature.
>>> for x in range(10, 13):
...     Article(headline="Article %s" % x, pub_date=datetime(2006, 10, 6)).save()

# With orphans set to 3 and 10 items per page, we should get all 12 items on a single page.
>>> paginator = Paginator(Article.objects.all(), 10, orphans=3)
>>> paginator.num_pages
1

# With orphans only set to 1, we should get two pages.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=1)
>>> paginator.num_pages
2

# LEGACY: With orphans set to 3 and 10 items per page, we should get all 12 items on a single page.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=3)
>>> paginator.pages
1

# LEGACY: With orphans only set to 1, we should get two pages.
>>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=1)
>>> paginator.pages
2
"""}
<|endoftext|>


<commit_before>from mock import MagicMock

from paradrop.confd import firewall

def test_ConfigRedirect_commands_dnat():
    """
    Test DNAT command generation
    """
    eth0 = MagicMock()
    eth0.config_ifname = "eth0"

    wanZone = MagicMock()
    wanZone.interfaces.return_value = [eth0]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone
    }

    config = firewall.ConfigRedirect()
    config.manager = MagicMock()
    config.target = "DNAT"
    config.proto = "tcp"
    config.src = "wan"

    config.src_ip = "1.2.3.4"
    config.src_dip = "192.168.1.1"
    config.src_port = 80
    config.src_dport = 8000
    config.dest_ip = "192.168.2.1"

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump DNAT --to-destination 192.168.2.1" in cmd

    config.dest_port = 9000

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump DNAT --to-destination 192.168.2.1:9000" in cmd

    config.dest_ip = None

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump REDIRECT --to-port 9000" in cmd

def test_ConfigRules():
    eth0 = MagicMock()
    eth0.config_ifname = "eth0"

    eth1 = MagicMock()
    eth1.config_ifname = "eth1"

    wanZone = MagicMock()
    wanZone.interfaces.return_value = [eth0]

    lanZone = MagicMock()
    lanZone.interfaces.return_value = [eth1]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone,
        ("firewall", "zone", "lan"): lanZone
    }

    config = firewall.ConfigRule()
    config.src = "wan"
    config.src_ip = "1.1.1.0/24"
    config.proto = "tcp"
    config.dest_ip = "192.168.1.1"
    config.dest_port = "80"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1

    config = firewall.ConfigRule()
    config.src = "wan"
    config.dest = "lan"
    config.src_ip = "1.1.1.0/24"
    config.proto = "tcp"
    config.dest_ip = "192.168.1.1"
    config.dest_port = "80"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1

    config = firewall.ConfigRule()
    config.dest = "wan"
    config.src_port = 53
    config.proto = "udp"
    config.dest_ip = "255.255.255.255"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1
<commit_msg>Added unit tests for new firewall conf sections.<commit_after>from mock import MagicMock

from paradrop.confd import firewall

def test_ConfigRedirect_commands_dnat():
    """
    Test DNAT command generation
    """
    eth0 = MagicMock()
    eth0.config_ifname = "eth0"

    wanZone = MagicMock()
    wanZone.interfaces.return_value = [eth0]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone
    }

    config = firewall.ConfigRedirect()
    config.manager = MagicMock()
    config.target = "DNAT"
    config.proto = "tcp"
    config.src = "wan"

    config.src_ip = "1.2.3.4"
    config.src_dip = "192.168.1.1"
    config.src_port = 80
    config.src_dport = 8000
    config.dest_ip = "192.168.2.1"

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump DNAT --to-destination 192.168.2.1" in cmd

    config.dest_port = 9000

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump DNAT --to-destination 192.168.2.1:9000" in cmd

    config.dest_ip = None

    commands = config.apply(allConfigs)
    for cmd in commands:
        print(cmd[1])
    assert len(commands) == 1

    cmd = commands[0][1]
    assert "--source 1.2.3.4" in cmd
    assert "--destination 192.168.1.1" in cmd
    assert "--sport 80" in cmd
    assert "--dport 8000" in cmd
    assert "--jump REDIRECT --to-port 9000" in cmd

def test_ConfigDefaults():
    config = firewall.ConfigDefaults()

    allConfigs = {}

    commands = config.apply(allConfigs)
    print(commands)
    assert len(commands) == 23

    commands = config.revert(allConfigs)
    assert len(commands) == 23

def test_ConfigZone():
    wanInterface = MagicMock()
    wanInterface.config_ifname = "eth0"

    allConfigs = {
        ("network", "interface", "wan"): wanInterface
    }

    config = firewall.ConfigZone()
    config.name = "wan"
    config.network = ["wan"]
    config.conntrack = True
    config.masq = True

    config.manager = MagicMock()
    config.manager.forwardingCount = 0
    config.manager.conntrackLoaded = False

    commands = config.apply(allConfigs)
    assert len(commands) == 17

    commands = config.revert(allConfigs)
    assert len(commands) == 16

def test_ConfigForwarding():
    lanInterface = MagicMock()

    wanZone = MagicMock()

    lanZone = MagicMock()
    lanZone.network = ["lan"]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone,
        ("firewall", "zone", "lan"): lanZone,
        ("network", "interface", "lan"): lanInterface
    }

    config = firewall.ConfigForwarding()
    config.src = "lan"
    config.dest = "wan"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1

def test_ConfigRules():
    eth0 = MagicMock()
    eth0.config_ifname = "eth0"

    eth1 = MagicMock()
    eth1.config_ifname = "eth1"

    wanZone = MagicMock()
    wanZone.interfaces.return_value = [eth0]

    lanZone = MagicMock()
    lanZone.interfaces.return_value = [eth1]

    allConfigs = {
        ("firewall", "zone", "wan"): wanZone,
        ("firewall", "zone", "lan"): lanZone
    }

    config = firewall.ConfigRule()
    config.src = "wan"
    config.src_ip = "1.1.1.0/24"
    config.proto = "tcp"
    config.dest_ip = "192.168.1.1"
    config.dest_port = "80"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1

    config = firewall.ConfigRule()
    config.src = "wan"
    config.dest = "lan"
    config.src_ip = "1.1.1.0/24"
    config.proto = "tcp"
    config.dest_ip = "192.168.1.1"
    config.dest_port = "80"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1

    config = firewall.ConfigRule()
    config.dest = "wan"
    config.src_port = 53
    config.proto = "udp"
    config.dest_ip = "255.255.255.255"
    config.target = "ACCEPT"

    commands = config.apply(allConfigs)
    assert len(commands) == 1

    commands = config.revert(allConfigs)
    assert len(commands) == 1
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

import os
import unittest

from opengem import region
from opengem.parser import shaml_output

FILES_KNOWN_TO_FAIL = ['ShamlOutputFile-fail-missing_required_attribute.xml',
                       'ShamlOutputFile-fail-attribute_type_mismatch.xml',
                       'ShamlOutputFile-fail-ambiguous_descriptor.xml',
                       'ShamlOutputFile-fail-missing_descriptor.xml',
                       'ShamlOutputFile-fail-IML_type_mismatch.xml',
                       'ShamlOutputFile-fail-missing_IML.xml',
                       'ShamlOutputFile-fail-illegal_gml_pos.xml',
                       'ShamlOutputFile-fail-curve_values_type_mismatch.xml',
                       'ShamlOutputFile-fail-missing_curve_vs30.xml']

TEST_FILE = 'ShamlOutputFile-test.xml'

data_dir = os.path.join(os.path.dirname(__file__), 'data')

class ShamlOutputFileTestCase(unittest.TestCase):

    def test_shamlfiles_known_to_fail(self):
        for testfile in FILES_KNOWN_TO_FAIL:
            shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                              testfile))

            value_error_found = False
            try:
                # just loop through generator, in order to trigger exception
                for point, attributes in shaml:
                    pass
            except ValueError:
                # this is the exception we are expecting
                value_error_found = True
            except Exception, e:
                raise RuntimeError, "unexpected exception: %s" % e

            self.assertTrue(value_error_found,
                "expected ValueError not raised in test file %s" % testfile)

    def test_filter_region_constraint_known_to_fail(self):

        # set region in which no site is found in input file
        region_constraint = region.RegionConstraint.from_simple((170.0, -80.0),
                                                                (175.0, -85.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        ctr = None

        # this loop is not expected to be entered - generator should
        # not yield any item
        for ctr, shaml_item in enumerate(shaml.filter(region_constraint)):
            pass

        # ensure that generator didn't yield an item
        self.assertTrue(ctr is None,
            "filter yielded item(s) although no items were expected")

    def test_filter_region_constraint_one_site(self):

        # look for sites within specified rectangle
        # constraint is met by one and only one site in the example file
        # (lon=16.35/lat=48.25)
        region_constraint = region.RegionConstraint.from_simple((16.0, 49.0),
                                                                (17.0, 48.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        expected_result = [(region.Point(16.35, 48.25),
                           {'IMT': 'MMI',
                            'IDmodel': 'MMI_3_1',
                            'timeSpanDuration': 50.0,
                            'endBranchLabel': '3_1',
                            'IML': [10.0, 20.0, 30.0],
                            'maxProb': 0.9,
                            'minProb': 0.1,
                            'Values': [0.005, 0.007, 0.009],
                            'vs30': 760.0})]

        ctr = None
        for ctr, (shaml_point, shaml_attr) in enumerate(
            shaml.filter(region_constraint)):

            # check topological equality for points
            self.assertTrue(shaml_point.equals(expected_result[ctr][0]),
                "filter yielded unexpected point at position %s: %s, %s" % (
                ctr, shaml_point, expected_result[ctr][0]))

            self.assertTrue(shaml_attr == expected_result[ctr][1],
                "filter yielded unexpected attribute values at position " \
                "%s: %s, %s" % (ctr, shaml_attr, expected_result[ctr][1]))

        # ensure that generator yielded at least one item
        self.assertTrue(ctr is not None,
            "filter yielded nothing although %s item(s) were expected" % \
            len(expected_result))

        # ensure that generator returns exactly the number of items of the
        # expected result list
        self.assertTrue(ctr == len(expected_result)-1,
            "filter yielded wrong number of items (%s), expected were %s" % (
                ctr+1, len(expected_result)))

    def test_filter_region_constraint_all_sites(self):

        # specified rectangle contains all sites in example file
        region_constraint = region.RegionConstraint.from_simple((-20.0, 80.0),
                                                                (40.0, 0.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        expected_result_ctr = 10
        ctr = None

        # just loop through iterator in order to count items
        for ctr, (shaml_point, shaml_attr) in enumerate(
            shaml.filter(region_constraint)):
            pass

        # ensure that generator yielded at least one item
        self.assertTrue(ctr is not None,
            "filter yielded nothing although %s item(s) were expected" % \
            expected_result_ctr)

        # ensure that generator returns exactly the number of items of the
        # expected result list
        self.assertTrue(ctr == expected_result_ctr-1,
            "filter yielded wrong number of items (%s), expected were %s" % (
                ctr+1, expected_result_ctr))

    def test_filter_attribute_constraint(self):
        """ This test uses the attribute constraint filter to select items
        from the input file. We assume here that the parser yields the
        items in the same order as specified in the example XML file. In
        a general case it would be better not to assume the order of
        yielded items to be known, but to locate each yielded result
        item in a set of expected results.
        """

        test_attribute_dicts = [
            {'IMT': 'PGA'},
            {'endBranchLabel': '1_2'},
            {'IMT': 'PGV', 'IML': [100.0, 200.0, 300.0]}
        ]

        expected_results = [ [(region.Point(2.35, 48.85),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_1',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_1',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.1, 0.2, 0.3],
                                'vs30': 760.0}),
                              (region.Point(12.45, 41.90),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_1',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_1',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.1, 0.2, 0.3],
                                'vs30': 760.0}),
                              (region.Point(-0.2, 51.45),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0}),
                              (region.Point(13.40, 52.50),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_3',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_3',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.001, 0.002, 0.003],
                                'vs30': 760.0})],
                             [(region.Point(-0.2, 51.45),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0}),
                              (region.Point(-0.2, 51.45),
                                {'IMT': 'PGV',
                                'IDmodel': 'PGV_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [10.0, 20.0, 30.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0})],
                             [(region.Point(13.40, 52.50),
                                {'IMT': 'PGV',
                                'IDmodel': 'PGV_2_1',
                                'timeSpanDuration': 20.0,
                                'endBranchLabel': '2_1',
                                'IML': [100.0, 200.0, 300.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.005, 0.007, 0.009],
                                'vs30': 760.0})]
                           ]

        # set a region constraint that inlcudes all points
        region_constraint = region.RegionConstraint.from_simple((-20.0, 80.0),
                                                                (40.0, 0.0))
        for attr_test_ctr, curr_attribute_dict in enumerate(
            test_attribute_dicts):
            attribute_constraint = \
                shaml_output.ShamlOutputConstraint(curr_attribute_dict)

            shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                              TEST_FILE))

            ctr = None
            for ctr, (shaml_point, shaml_attr) in enumerate(
                shaml.filter(region_constraint, attribute_constraint)):

                # check topological equality for points
                self.assertTrue(shaml_point.equals(
                    expected_results[attr_test_ctr][ctr][0]),
                    "filter yielded unexpected point at position %s: %s, %s" \
                    % (ctr, shaml_point,
                       expected_results[attr_test_ctr][ctr][0]))

                self.assertTrue(shaml_attr == expected_results[
                    attr_test_ctr][ctr][1],
                    "filter yielded unexpected attribute values at position" \
                    " %s: %s, %s" % (ctr, shaml_attr,
                                     expected_results[attr_test_ctr][ctr][1]))

            # ensure that generator yielded at least one item
            self.assertTrue(ctr is not None,
                "filter yielded nothing although %s item(s) were expected" % \
                len(expected_results[attr_test_ctr]))

            # ensure that generator returns exactly the number of items of the
            # expected result list
            self.assertTrue(ctr == len(expected_results[attr_test_ctr])-1,
                "filter yielded wrong number of items (%s), expected were %s" \
                % (ctr+1, len(expected_results[attr_test_ctr])))
<commit_msg>test for known failures in example files: use assertRaises()<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

import os
import unittest

from opengem import region
from opengem.parser import shaml_output

FILES_KNOWN_TO_FAIL = ['ShamlOutputFile-fail-missing_required_attribute.xml',
                       'ShamlOutputFile-fail-attribute_type_mismatch.xml',
                       'ShamlOutputFile-fail-ambiguous_descriptor.xml',
                       'ShamlOutputFile-fail-missing_descriptor.xml',
                       'ShamlOutputFile-fail-IML_type_mismatch.xml',
                       'ShamlOutputFile-fail-missing_IML.xml',
                       'ShamlOutputFile-fail-illegal_gml_pos.xml',
                       'ShamlOutputFile-fail-curve_values_type_mismatch.xml',
                       'ShamlOutputFile-fail-missing_curve_vs30.xml']

TEST_FILE = 'ShamlOutputFile-test.xml'

data_dir = os.path.join(os.path.dirname(__file__), 'data')

class ShamlOutputFileTestCase(unittest.TestCase):

    def test_shamlfiles_known_to_fail(self):
        for testfile in FILES_KNOWN_TO_FAIL:
            shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                              testfile))

            self.assertRaises(ValueError, map, None, shaml)

    def test_filter_region_constraint_known_to_fail(self):

        # set region in which no site is found in input file
        region_constraint = region.RegionConstraint.from_simple((170.0, -80.0),
                                                                (175.0, -85.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        ctr = None

        # this loop is not expected to be entered - generator should
        # not yield any item
        for ctr, shaml_item in enumerate(shaml.filter(region_constraint)):
            pass

        # ensure that generator didn't yield an item
        self.assertTrue(ctr is None,
            "filter yielded item(s) although no items were expected")

    def test_filter_region_constraint_one_site(self):

        # look for sites within specified rectangle
        # constraint is met by one and only one site in the example file
        # (lon=16.35/lat=48.25)
        region_constraint = region.RegionConstraint.from_simple((16.0, 49.0),
                                                                (17.0, 48.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        expected_result = [(region.Point(16.35, 48.25),
                           {'IMT': 'MMI',
                            'IDmodel': 'MMI_3_1',
                            'timeSpanDuration': 50.0,
                            'endBranchLabel': '3_1',
                            'IML': [10.0, 20.0, 30.0],
                            'maxProb': 0.9,
                            'minProb': 0.1,
                            'Values': [0.005, 0.007, 0.009],
                            'vs30': 760.0})]

        ctr = None
        for ctr, (shaml_point, shaml_attr) in enumerate(
            shaml.filter(region_constraint)):

            # check topological equality for points
            self.assertTrue(shaml_point.equals(expected_result[ctr][0]),
                "filter yielded unexpected point at position %s: %s, %s" % (
                ctr, shaml_point, expected_result[ctr][0]))

            self.assertTrue(shaml_attr == expected_result[ctr][1],
                "filter yielded unexpected attribute values at position " \
                "%s: %s, %s" % (ctr, shaml_attr, expected_result[ctr][1]))

        # ensure that generator yielded at least one item
        self.assertTrue(ctr is not None,
            "filter yielded nothing although %s item(s) were expected" % \
            len(expected_result))

        # ensure that generator returns exactly the number of items of the
        # expected result list
        self.assertTrue(ctr == len(expected_result)-1,
            "filter yielded wrong number of items (%s), expected were %s" % (
                ctr+1, len(expected_result)))

    def test_filter_region_constraint_all_sites(self):

        # specified rectangle contains all sites in example file
        region_constraint = region.RegionConstraint.from_simple((-20.0, 80.0),
                                                                (40.0, 0.0))
        shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                          TEST_FILE))

        expected_result_ctr = 10
        ctr = None

        # just loop through iterator in order to count items
        for ctr, (shaml_point, shaml_attr) in enumerate(
            shaml.filter(region_constraint)):
            pass

        # ensure that generator yielded at least one item
        self.assertTrue(ctr is not None,
            "filter yielded nothing although %s item(s) were expected" % \
            expected_result_ctr)

        # ensure that generator returns exactly the number of items of the
        # expected result list
        self.assertTrue(ctr == expected_result_ctr-1,
            "filter yielded wrong number of items (%s), expected were %s" % (
                ctr+1, expected_result_ctr))

    def test_filter_attribute_constraint(self):
        """ This test uses the attribute constraint filter to select items
        from the input file. We assume here that the parser yields the
        items in the same order as specified in the example XML file. In
        a general case it would be better not to assume the order of
        yielded items to be known, but to locate each yielded result
        item in a set of expected results.
        """

        test_attribute_dicts = [
            {'IMT': 'PGA'},
            {'endBranchLabel': '1_2'},
            {'IMT': 'PGV', 'IML': [100.0, 200.0, 300.0]}
        ]

        expected_results = [ [(region.Point(2.35, 48.85),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_1',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_1',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.1, 0.2, 0.3],
                                'vs30': 760.0}),
                              (region.Point(12.45, 41.90),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_1',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_1',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.1, 0.2, 0.3],
                                'vs30': 760.0}),
                              (region.Point(-0.2, 51.45),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0}),
                              (region.Point(13.40, 52.50),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_3',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_3',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.001, 0.002, 0.003],
                                'vs30': 760.0})],
                             [(region.Point(-0.2, 51.45),
                                {'IMT': 'PGA',
                                'IDmodel': 'PGA_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [1.0, 2.0, 3.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0}),
                              (region.Point(-0.2, 51.45),
                                {'IMT': 'PGV',
                                'IDmodel': 'PGV_1_2',
                                'timeSpanDuration': 50.0,
                                'endBranchLabel': '1_2',
                                'IML': [10.0, 20.0, 30.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.01, 0.02, 0.03],
                                'vs30': 760.0})],
                             [(region.Point(13.40, 52.50),
                                {'IMT': 'PGV',
                                'IDmodel': 'PGV_2_1',
                                'timeSpanDuration': 20.0,
                                'endBranchLabel': '2_1',
                                'IML': [100.0, 200.0, 300.0],
                                'maxProb': 0.9,
                                'minProb': 0.1,
                                'Values': [0.005, 0.007, 0.009],
                                'vs30': 760.0})]
                           ]

        # set a region constraint that inlcudes all points
        region_constraint = region.RegionConstraint.from_simple((-20.0, 80.0),
                                                                (40.0, 0.0))
        for attr_test_ctr, curr_attribute_dict in enumerate(
            test_attribute_dicts):
            attribute_constraint = \
                shaml_output.ShamlOutputConstraint(curr_attribute_dict)

            shaml = shaml_output.ShamlOutputFile(os.path.join(data_dir,
                                                              TEST_FILE))

            ctr = None
            for ctr, (shaml_point, shaml_attr) in enumerate(
                shaml.filter(region_constraint, attribute_constraint)):

                # check topological equality for points
                self.assertTrue(shaml_point.equals(
                    expected_results[attr_test_ctr][ctr][0]),
                    "filter yielded unexpected point at position %s: %s, %s" \
                    % (ctr, shaml_point,
                       expected_results[attr_test_ctr][ctr][0]))

                self.assertTrue(shaml_attr == expected_results[
                    attr_test_ctr][ctr][1],
                    "filter yielded unexpected attribute values at position" \
                    " %s: %s, %s" % (ctr, shaml_attr,
                                     expected_results[attr_test_ctr][ctr][1]))

            # ensure that generator yielded at least one item
            self.assertTrue(ctr is not None,
                "filter yielded nothing although %s item(s) were expected" % \
                len(expected_results[attr_test_ctr]))

            # ensure that generator returns exactly the number of items of the
            # expected result list
            self.assertTrue(ctr == len(expected_results[attr_test_ctr])-1,
                "filter yielded wrong number of items (%s), expected were %s" \
                % (ctr+1, len(expected_results[attr_test_ctr])))
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2012  FinalsClub Foundation

from django.contrib.sites.models import Site
from django.http import HttpResponse
from django.views.generic import DetailView
from django.views.generic import FormView
from django.views.generic import View
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import get_object_or_404

from karmaworld.apps.notes.models import Note
from karmaworld.apps.notes.forms import NoteForm

class NoteDetailView(DetailView):
    """ Class-based view for the note html page """
    model = Note
    context_object_name = u"note" # name passed to template

    def get_context_data(self, **kwargs):
        """ add the hostname to the PDF embed for PDF.js
            from the Sites admin database record """
        kwargs = {
            'hostname': Site.objects.get_current()
        }
        return super(NoteDetailView, self).get_context_data(**kwargs)

class NoteSaveView(FormView, SingleObjectMixin):
    """ Save a Note and then view the page,
        behaves the same as NoteDetailView, except for saving the
        NoteForm ModelForm
    """
    form_class = NoteForm
    model = Note
    template_name = 'notes/note_detail.html'

    def get_context_data(self, **kwargs):
        context = {
            'object': self.get_object(),
        }
        print "get context for NoteSaveView"
        return super(NoteSaveView, self).get_context_data(**context)

    def get_success_url(self):
        """ On form submission success, redirect to what url """
        #TODO: redirect to note slug if possible (auto-slugify)
        return u'/{school_slug}/{course_slug}?url=/{school_slug}/{course_slug}/{pk}&name={name}&thankyou'.format(
                school_slug=self.object.course.school.slug,
                course_slug=self.object.course.slug,
                pk=self.object.pk,
                name=self.object.name
            )

    def form_valid(self, form):
        """ Actions to take if the submitted form is valid
            namely, saving the new data to the existing note object
        """
        self.object = self.get_object()
        if len(form.cleaned_data['name'].strip()) > 0:
            self.object.name = form.cleaned_data['name']
        self.object.year = form.cleaned_data['year']
        # use *arg expansion to pass tags a list of tags
        self.object.tags.add(*form.cleaned_data['tags'])
        self.object.save()
        return super(NoteSaveView, self).form_valid(form)

    def form_invalid(self, form):
        """ Do stuff when the form is invalid !!! TODO """
        # TODO: implement def form_invalid for returning a form with input and error
        print "running form_invalid"
        print form
        print form.errors

class NoteView(View):
    """ Notes superclass that wraps http methods """

    def get(self, request, *args, **kwargs):
        view = NoteDetailView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = NoteSaveView.as_view()
        return view(request, *args, **kwargs)

class RawNoteDetailView(DetailView):
    """ Class-based view for the raw note html for iframes """
    template_name = u'notes/note_raw.html'
    context_object_name = u"note"
    model = Note

class PDFView(DetailView):
    """ Render PDF files in an iframe based on ID"""
    template_name = u'partial/pdfembed.html'
    model = Note

<commit_msg>update the pdf view to create the correct path to pdf media<commit_after>#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2012  FinalsClub Foundation

import os

from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponse
from django.views.generic import DetailView
from django.views.generic import FormView
from django.views.generic import View
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import get_object_or_404

from karmaworld.apps.notes.models import Note
from karmaworld.apps.notes.forms import NoteForm

class NoteDetailView(DetailView):
    """ Class-based view for the note html page """
    model = Note
    context_object_name = u"note" # name passed to template

    def get_context_data(self, **kwargs):
        """ Generate custom context for the page rendering a Note
            + if pdf, set the `pdf` flag
        """
        #kwargs['file_url'] = os.path.basename(_path)
        #kwargs['hostname'] = Site.objects.get_current()

        def is_pdf(self):
            _path = self.object.note_file.name
            _, _extension = os.path.splitext(_path)
            if _extension.lower() == '.pdf':
                return True
            return False

        kwargs['pdf'] = is_pdf(self)

        return super(NoteDetailView, self).get_context_data(**kwargs)

class NoteSaveView(FormView, SingleObjectMixin):
    """ Save a Note and then view the page,
        behaves the same as NoteDetailView, except for saving the
        NoteForm ModelForm
    """
    form_class = NoteForm
    model = Note
    template_name = 'notes/note_detail.html'

    def get_context_data(self, **kwargs):
        context = {
            'object': self.get_object(),
        }
        print "get context for NoteSaveView"
        return super(NoteSaveView, self).get_context_data(**context)

    def get_success_url(self):
        """ On form submission success, redirect to what url """
        #TODO: redirect to note slug if possible (auto-slugify)
        return u'/{school_slug}/{course_slug}?url=/{school_slug}/{course_slug}/{pk}&name={name}&thankyou'.format(
                school_slug=self.object.course.school.slug,
                course_slug=self.object.course.slug,
                pk=self.object.pk,
                name=self.object.name
            )

    def form_valid(self, form):
        """ Actions to take if the submitted form is valid
            namely, saving the new data to the existing note object
        """
        self.object = self.get_object()
        if len(form.cleaned_data['name'].strip()) > 0:
            self.object.name = form.cleaned_data['name']
        self.object.year = form.cleaned_data['year']
        # use *arg expansion to pass tags a list of tags
        self.object.tags.add(*form.cleaned_data['tags'])
        self.object.save()
        return super(NoteSaveView, self).form_valid(form)

    def form_invalid(self, form):
        """ Do stuff when the form is invalid !!! TODO """
        # TODO: implement def form_invalid for returning a form with input and error
        print "running form_invalid"
        print form
        print form.errors

class NoteView(View):
    """ Notes superclass that wraps http methods """

    def get(self, request, *args, **kwargs):
        view = NoteDetailView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = NoteSaveView.as_view()
        return view(request, *args, **kwargs)

class RawNoteDetailView(DetailView):
    """ Class-based view for the raw note html for iframes """
    template_name = u'notes/note_raw.html'
    context_object_name = u"note"
    model = Note

class PDFView(DetailView):
    """ Render PDF files in an iframe based on ID"""
    template_name = u'partial/pdfembed.html'
    model = Note

    def get_context_data(self, **kwargs):
        """ Generate a path to the pdf file associated with this note
            by generating a path to the MEDIA_URL by hand """
        # FIXME: There may be an undocumented,
        #   but better way of handling media files in django

        kwargs['pdf_path'] = "{0}{1}".format(settings.MEDIA_URL,
            os.path.basename(self.object.note_file.name))

        return super(PDFView, self).get_context_data(**kwargs)
<|endoftext|>


<commit_before><commit_msg>Update Q2-Rabbits Multiplying: recursive solution<commit_after><|endoftext|>