<commit_before>import http
import json

from openbrokerapi import errors
from openbrokerapi.catalog import ServicePlan
from openbrokerapi.service_broker import ProvisionedServiceSpec, ProvisionDetails, ProvisionState, Service
from tests import BrokerTestCase

class ProvisioningTest(BrokerTestCase):
    def setUp(self):
        self.broker.catalog.return_value = [
            Service(
                id='service-guid-here',
                name='',
                description='',
                bindable=True,
                plans=[
                    ServicePlan('plan-guid-here', name='', description='')
                ])
        ]

    def test_provisioning_called_with_the_right_values(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                "context": {
                    "organization_guid": "org-guid-here",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, True)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.parameters, dict(parameter1=1))
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")
        self.assertEqual(actual_details.context["organization_guid"], "org-guid-here")
        self.assertEqual(actual_details.context["space_guid"], "space-guid-here")

    def test_provisining_called_just_with_required_fields(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "context": {
                    "organization_guid": "org-guid-here",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_provisining_optional_org_and_space_if_available_in_context(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                "X-Broker-Api-Version": "2.13",
                "Content-Type": "application/json",
                "Authorization": self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_provisining_ignores_unknown_parameters(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "unknown": "unknown"
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_returns_201_if_created(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(
            dashboard_url="dash_url",
            operation="operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.CREATED)
        self.assertEqual(response.json, dict(
            dashboard_url="dash_url",
            operation="operation_str"
        ))

    def test_returns_202_if_provisioning_in_progress(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(
            ProvisionState.IS_ASYNC,
            "dash_url",
            "operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.ACCEPTED)
        self.assertEqual(response.json, dict(
            dashboard_url="dash_url",
            operation="operation_str"
        ))

    def test_returns_409_if_already_exists_but_is_not_equal(self):
        self.broker.provision.side_effect = errors.ErrInstanceAlreadyExists()

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.CONFLICT)
        self.assertEqual(response.json, {})

    def test_returns_422_if_async_required_but_not_supported(self):
        self.broker.provision.side_effect = errors.ErrAsyncRequired()

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.UNPROCESSABLE_ENTITY)
        self.assertEqual(response.json, dict(
            error="AsyncRequired",
            description="This service plan requires client support for asynchronous service operations."
        ))

    def test_returns_400_if_missing_mandatory_data(self):
        self.broker.provision.side_effect = errors.ErrInvalidParameters('Required parameters not provided.')

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                "X-Broker-Api-Version": "2.13",
                "Content-Type": "application/json",
                "Authorization": self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json, dict(
            error="InvalidParameters",
            description="Required parameters not provided."
        ))

    def test_returns_400_if_missing_org_and_space_guids_data(self):
        self.broker.provision.return_value = self.broker.provision.return_value = ProvisionedServiceSpec(
            ProvisionState.IS_ASYNC,
            "dash_url",
            "operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code)
        self.assertEqual(dict(
            description="Organization and space guid are required."
        ), response.json)

    def test_returns_200_if_identical_service_exists(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(ProvisionState.IDENTICAL_ALREADY_EXISTS)

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.OK)
        self.assertEqual(response.json, dict())

    def test_returns_400_if_request_does_not_contain_content_type_header(self):
        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description='Improper Content-Type header. Expecting "application/json"'))

    def test_returns_400_if_request_does_not_contain_valid_json_body(self):
        response = self.client.put(
            "/v2/service_instances/abc",
            data='I am not a json object',
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description='Improper Content-Type header. Expecting "application/json"'))

    def test_returns_400_if_context_organization_guid_mismatch(self):
        response = self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                'context': {
                    "organization_guid": "a_mismatching_org",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description="organization_guid does not match with context.organization_guid"))

    def test_returns_400_if_context_space_guid_mismatch(self):
        response = self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                'context': {
                    "organization_guid": "org-guid-here",
                    "space_guid": "a_mismatching_space",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json, dict(description="space_guid does not match with context.space_guid"))
<commit_msg>Complete unfinished test<commit_after>import http
import json

from openbrokerapi import errors
from openbrokerapi.catalog import ServicePlan
from openbrokerapi.service_broker import ProvisionedServiceSpec, ProvisionDetails, ProvisionState, Service
from tests import BrokerTestCase

class ProvisioningTest(BrokerTestCase):
    def setUp(self):
        self.broker.catalog.return_value = [
            Service(
                id='service-guid-here',
                name='',
                description='',
                bindable=True,
                plans=[
                    ServicePlan('plan-guid-here', name='', description='')
                ])
        ]

    def test_provisioning_called_with_the_right_values(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                "context": {
                    "organization_guid": "org-guid-here",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, True)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.parameters, dict(parameter1=1))
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")
        self.assertEqual(actual_details.context["organization_guid"], "org-guid-here")
        self.assertEqual(actual_details.context["space_guid"], "space-guid-here")

    def test_provisining_called_just_with_required_fields(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "context": {
                    "organization_guid": "org-guid-here",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_provisining_optional_org_and_space_if_available_in_context(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                "X-Broker-Api-Version": "2.13",
                "Content-Type": "application/json",
                "Authorization": self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_provisining_ignores_unknown_parameters(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(dashboard_url="dash_url", operation="operation_str")

        self.client.put(
            "/v2/service_instances/here-instance-id",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "unknown": "unknown"
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        actual_instance_id, actual_details, actual_async_allowed = self.broker.provision.call_args[0]
        self.assertEqual(actual_instance_id, "here-instance-id")
        self.assertEqual(actual_async_allowed, False)

        self.assertIsInstance(actual_details, ProvisionDetails)
        self.assertEqual(actual_details.service_id, "service-guid-here")
        self.assertEqual(actual_details.plan_id, "plan-guid-here")
        self.assertEqual(actual_details.organization_guid, "org-guid-here")
        self.assertEqual(actual_details.space_guid, "space-guid-here")

        self.assertIsNone(actual_details.parameters)

    def test_returns_201_if_created(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(
            dashboard_url="dash_url",
            operation="operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.CREATED)
        self.assertEqual(response.json, dict(
            dashboard_url="dash_url",
            operation="operation_str"
        ))

    def test_returns_202_if_provisioning_in_progress(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(
            ProvisionState.IS_ASYNC,
            "dash_url",
            "operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.ACCEPTED)
        self.assertEqual(response.json, dict(
            dashboard_url="dash_url",
            operation="operation_str"
        ))

    def test_returns_409_if_already_exists_but_is_not_equal(self):
        self.broker.provision.side_effect = errors.ErrInstanceAlreadyExists()

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.CONFLICT)
        self.assertEqual(response.json, {})

    def test_returns_422_if_async_required_but_not_supported(self):
        self.broker.provision.side_effect = errors.ErrAsyncRequired()

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.UNPROCESSABLE_ENTITY)
        self.assertEqual(response.json, dict(
            error="AsyncRequired",
            description="This service plan requires client support for asynchronous service operations."
        ))

    def test_returns_400_if_missing_mandatory_data(self):
        self.broker.provision.side_effect = errors.ErrInvalidParameters('Required parameters not provided.')

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                "X-Broker-Api-Version": "2.13",
                "Content-Type": "application/json",
                "Authorization": self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json, dict(
            error="InvalidParameters",
            description="Required parameters not provided."
        ))

    def test_returns_400_if_missing_org_and_space_guids_data(self):
        self.broker.provision.return_value = self.broker.provision.return_value = ProvisionedServiceSpec(
            ProvisionState.IS_ASYNC,
            "dash_url",
            "operation_str"
        )

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(http.HTTPStatus.BAD_REQUEST, response.status_code)
        self.assertEqual(dict(
            description="Organization and space guid are required."
        ), response.json)

    def test_returns_200_if_identical_service_exists(self):
        self.broker.provision.return_value = ProvisionedServiceSpec(ProvisionState.IDENTICAL_ALREADY_EXISTS)

        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.OK)
        self.assertEqual(response.json, dict())

    def test_returns_400_if_request_does_not_contain_content_type_header(self):
        response = self.client.put(
            "/v2/service_instances/abc",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description='Improper Content-Type header. Expecting "application/json"'))

    def test_returns_400_if_request_does_not_contain_valid_json_body(self):
        response = self.client.put(
            "/v2/service_instances/abc",
            data='I am not a json object',
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description='Improper Content-Type header. Expecting "application/json"'))

    def test_returns_400_if_context_organization_guid_mismatch(self):
        response = self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                'context': {
                    "organization_guid": "a_mismatching_org",
                    "space_guid": "space-guid-here",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json,
                         dict(description="organization_guid does not match with context.organization_guid"))

    def test_returns_400_if_context_space_guid_mismatch(self):
        response = self.client.put(
            "/v2/service_instances/here-instance-id?accepts_incomplete=true",
            data=json.dumps({
                "service_id": "service-guid-here",
                "plan_id": "plan-guid-here",
                "organization_guid": "org-guid-here",
                "space_guid": "space-guid-here",
                "parameters": {
                    "parameter1": 1
                },
                'context': {
                    "organization_guid": "org-guid-here",
                    "space_guid": "a_mismatching_space",
                }
            }),
            headers={
                'X-Broker-Api-Version': '2.13',
                'Content-Type': 'application/json',
                'Authorization': self.auth_header
            })

        self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
        self.assertEqual(response.json, dict(description="space_guid does not match with context.space_guid"))
<|endoftext|>


<commit_before>import pytest

from Starfish.grid_tools import *
from Starfish.utils import create_log_lam_grid

@pytest.mark.skip("Needs to be reimplemented")
class TestRealSpectrum:
    '''
    We've done all of the previous tests using fake spectra. Now try some of the convolution tests using
    a real spectrum and examining what the result is.
    '''
    def setup_class(self):
        hdf5interface = HDF5Interface("libraries/PHOENIX_submaster.hdf5")
        wl = hdf5interface.wl
        self.spec = hdf5interface.load_file({"temp":6100, "logg":4.5, "Z": 0.0, "alpha":0.0})
        self.instrument = Reticon()
        self.wl_range = (5160, 5180)

    def test_plot_spectrum(self):
        spec = self.spec.copy()

    def test_stellar_convolve(self):
        spec = self.spec.copy()
        spec.stellar_convolve(20.)

    def test_instrument_convolve(self):
        spec = self.spec.copy()
        spec.instrument_convolve(self.instrument)

    def test_instrument_and_stellar_convolve(self):
        spec = self.spec.copy()
        spec.instrument_and_stellar_convolve(self.instrument, 20)

    def test_straight_line(self):
        wl_dict = create_log_lam_grid(3000, 13000, min_vc=2/C.c_kms)
        wl = wl_dict.pop("wl")
        fl = wl.copy()
        spec = LogLambdaSpectrum(wl,fl)
        spec.stellar_convolve(50.)
        #Basically, this shows that the up and down behaviour of the Fourier blending is not a problem. It is just
        #blending as if the spectrum wraps. Therefore the two edges are going to match as if it was circular because
        #the stellar kernel is CONVOLVING them TOGETHER, making what was once a 1 pixel transition from max to min now
        #take place over a couple pixels. Thus, there will be edge-effects if the two ends of the spectra aren't very close
<commit_msg>removed extraneous test file<commit_after><|endoftext|>


<commit_before>import uuid
from datetime import datetime
from unittest.mock import Mock, call

import pytest
from freezegun import freeze_time

from notifications_utils.clients.redis import (
    daily_limit_cache_key,
    rate_limit_cache_key,
)
from notifications_utils.clients.redis.redis_client import (
    RedisClient,
    prepare_value,
)

@pytest.fixture(scope='function')
def mocked_redis_pipeline():
    return Mock()

@pytest.fixture(scope='function')
def mocked_redis_client(app, mocked_redis_pipeline, mocker):
    app.config['REDIS_ENABLED'] = True
    return build_redis_client(app, mocked_redis_pipeline, mocker)

def build_redis_client(app, mocked_redis_pipeline, mocker):
    redis_client = RedisClient()
    redis_client.init_app(app)
    mocker.patch.object(redis_client.redis_store, 'get', return_value=100)
    mocker.patch.object(redis_client.redis_store, 'set')
    mocker.patch.object(redis_client.redis_store, 'hincrby')
    mocker.patch.object(redis_client.redis_store, 'hgetall',
                        return_value={b'template-1111': b'8', b'template-2222': b'8'})
    mocker.patch.object(redis_client.redis_store, 'hmset')
    mocker.patch.object(redis_client.redis_store, 'expire')
    mocker.patch.object(redis_client.redis_store, 'delete')
    mocker.patch.object(redis_client.redis_store, 'pipeline', return_value=mocked_redis_pipeline)

    return redis_client

def test_should_not_raise_exception_if_raise_set_to_false(app, caplog, mocker):
    mock_logger = mocker.patch('flask.Flask.logger')

    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception())
    redis_client.redis_store.set = Mock(side_effect=Exception())
    redis_client.redis_store.incr = Mock(side_effect=Exception())
    redis_client.redis_store.pipeline = Mock(side_effect=Exception())
    redis_client.redis_store.delete = Mock(side_effect=Exception())
    assert redis_client.get('get_key') is None
    assert redis_client.set('set_key', 'set_value') is None
    assert redis_client.incr('incr_key') is None
    assert redis_client.exceeded_rate_limit('rate_limit_key', 100, 100) is False
    assert redis_client.delete('delete_key') is None
    assert redis_client.delete('a', 'b', 'c') is None
    assert mock_logger.mock_calls == [
        call.exception('Redis error performing get on get_key'),
        call.exception('Redis error performing set on set_key'),
        call.exception('Redis error performing incr on incr_key'),
        call.exception('Redis error performing rate-limit-pipeline on rate_limit_key'),
        call.exception('Redis error performing delete on delete_key'),
        call.exception('Redis error performing delete on a, b, c'),
    ]

def test_should_raise_exception_if_raise_set_to_true(app):
    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception('get failed'))
    redis_client.redis_store.set = Mock(side_effect=Exception('set failed'))
    redis_client.redis_store.incr = Mock(side_effect=Exception('inc failed'))
    redis_client.redis_store.pipeline = Mock(side_effect=Exception('pipeline failed'))
    redis_client.redis_store.delete = Mock(side_effect=Exception('delete failed'))
    with pytest.raises(Exception) as e:
        redis_client.get('test', raise_exception=True)
    assert str(e.value) == 'get failed'
    with pytest.raises(Exception) as e:
        redis_client.set('test', 'test', raise_exception=True)
    assert str(e.value) == 'set failed'
    with pytest.raises(Exception) as e:
        redis_client.incr('test', raise_exception=True)
    assert str(e.value) == 'inc failed'
    with pytest.raises(Exception) as e:
        redis_client.exceeded_rate_limit('test', 100, 200, raise_exception=True)
    assert str(e.value) == 'pipeline failed'
    with pytest.raises(Exception) as e:
        redis_client.delete('test', raise_exception=True)
    assert str(e.value) == 'delete failed'

def test_should_not_call_set_if_not_enabled(mocked_redis_client):
    mocked_redis_client.active = False
    assert not mocked_redis_client.set('key', 'value')
    mocked_redis_client.redis_store.set.assert_not_called()

def test_should_call_set_if_enabled(mocked_redis_client):
    mocked_redis_client.set('key', 'value')
    mocked_redis_client.redis_store.set.assert_called_with('key', 'value', None, None, False, False)

def test_should_not_call_get_if_not_enabled(mocked_redis_client):
    mocked_redis_client.active = False
    mocked_redis_client.get('key')
    mocked_redis_client.redis_store.get.assert_not_called()

def test_should_not_call_redis_if_not_enabled_for_rate_limit_check(mocked_redis_client):
    mocked_redis_client.active = False
    mocked_redis_client.exceeded_rate_limit('key', 100, 200)
    mocked_redis_client.redis_store.pipeline.assert_not_called()

def test_should_call_get_if_enabled(mocked_redis_client):
    assert mocked_redis_client.get('key') == 100
    mocked_redis_client.redis_store.get.assert_called_with('key')

def test_should_build_cache_key_service_and_action(sample_service):
    with freeze_time("2016-01-01 12:00:00.000000"):
        assert daily_limit_cache_key(sample_service.id) == '{}-2016-01-01-count'.format(sample_service.id)

def test_should_build_daily_limit_cache_key(sample_service):
    assert rate_limit_cache_key(sample_service.id, 'TEST') == '{}-TEST'.format(sample_service.id)

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_add_correct_calls_to_the_pipe(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_client.exceeded_rate_limit("key", 100, 100)
    assert mocked_redis_client.redis_store.pipeline.called
    mocked_redis_pipeline.zadd.assert_called_with("key", {978350400.0: 978350400.0})
    mocked_redis_pipeline.zremrangebyscore.assert_called_with("key", '-inf', 978350300.0)
    mocked_redis_pipeline.zcard.assert_called_with("key")
    mocked_redis_pipeline.expire.assert_called_with("key", 100)
    assert mocked_redis_pipeline.execute.called

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_fail_request_if_over_limit(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 100, True]
    assert mocked_redis_client.exceeded_rate_limit("key", 99, 100)

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_allow_request_if_not_over_limit(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 100, True]
    assert not mocked_redis_client.exceeded_rate_limit("key", 101, 100)

@freeze_time("2001-01-01 12:00:00.000000")
def test_rate_limit_not_exceeded(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 80, True]
    assert not mocked_redis_client.exceeded_rate_limit("key", 90, 100)

def test_should_not_call_rate_limit_if_not_enabled(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_client.active = False

    assert not mocked_redis_client.exceeded_rate_limit('key', 100, 100)
    assert not mocked_redis_client.redis_store.pipeline.called

def test_delete(mocked_redis_client):
    key = 'hash-key'
    mocked_redis_client.delete(key)
    mocked_redis_client.redis_store.delete.assert_called_with(key)

def test_multi_delete(mocked_redis_client):
    mocked_redis_client.delete('a', 'b', 'c')
    mocked_redis_client.redis_store.delete.assert_called_with('a', 'b', 'c')

@pytest.mark.parametrize('input,output', [
    (b'asdf', b'asdf'),
    ('asdf', 'asdf'),
    (0, 0),
    (1.2, 1.2),
    (uuid.UUID(int=0), '00000000-0000-0000-0000-000000000000'),
    pytest.param({'a': 1}, None, marks=pytest.mark.xfail(raises=ValueError)),
    pytest.param(datetime.utcnow(), None, marks=pytest.mark.xfail(raises=ValueError)),
])
def test_prepare_value(input, output):
    assert prepare_value(input) == output

def test_delete_cache_keys(mocked_redis_client):
    delete_mock = Mock(return_value=4)
    mocked_redis_client.scripts = {'delete-keys-by-pattern': delete_mock}

    ret = mocked_redis_client.delete_cache_keys_by_pattern('foo')

    assert ret == 4
    delete_mock.assert_called_once_with(args=['foo'])

def test_delete_cache_keys_returns_zero_when_redis_disabled(mocked_redis_client):
    mocked_redis_client.active = False
    delete_mock = Mock()
    mocked_redis_client.scripts = {'delete-keys-by-pattern': delete_mock}

    ret = mocked_redis_client.delete_cache_keys_by_pattern('foo')

    assert delete_mock.called is False
    assert ret == 0
<commit_msg>Remove redundant "build" test helper function<commit_after>import uuid
from datetime import datetime
from unittest.mock import Mock, call

import pytest
from freezegun import freeze_time

from notifications_utils.clients.redis import (
    daily_limit_cache_key,
    rate_limit_cache_key,
)
from notifications_utils.clients.redis.redis_client import (
    RedisClient,
    prepare_value,
)

@pytest.fixture(scope='function')
def mocked_redis_pipeline():
    return Mock()

@pytest.fixture(scope='function')
def mocked_redis_client(app, mocked_redis_pipeline, mocker):
    app.config['REDIS_ENABLED'] = True

    redis_client = RedisClient()
    redis_client.init_app(app)

    mocker.patch.object(redis_client.redis_store, 'get', return_value=100)
    mocker.patch.object(redis_client.redis_store, 'set')
    mocker.patch.object(redis_client.redis_store, 'hincrby')
    mocker.patch.object(redis_client.redis_store, 'hmset')
    mocker.patch.object(redis_client.redis_store, 'expire')
    mocker.patch.object(redis_client.redis_store, 'delete')
    mocker.patch.object(redis_client.redis_store, 'pipeline', return_value=mocked_redis_pipeline)

    mocker.patch.object(
        redis_client.redis_store,
        'hgetall',
        return_value={b'template-1111': b'8', b'template-2222': b'8'}
    )

    return redis_client

def test_should_not_raise_exception_if_raise_set_to_false(app, caplog, mocker):
    mock_logger = mocker.patch('flask.Flask.logger')

    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception())
    redis_client.redis_store.set = Mock(side_effect=Exception())
    redis_client.redis_store.incr = Mock(side_effect=Exception())
    redis_client.redis_store.pipeline = Mock(side_effect=Exception())
    redis_client.redis_store.delete = Mock(side_effect=Exception())
    assert redis_client.get('get_key') is None
    assert redis_client.set('set_key', 'set_value') is None
    assert redis_client.incr('incr_key') is None
    assert redis_client.exceeded_rate_limit('rate_limit_key', 100, 100) is False
    assert redis_client.delete('delete_key') is None
    assert redis_client.delete('a', 'b', 'c') is None
    assert mock_logger.mock_calls == [
        call.exception('Redis error performing get on get_key'),
        call.exception('Redis error performing set on set_key'),
        call.exception('Redis error performing incr on incr_key'),
        call.exception('Redis error performing rate-limit-pipeline on rate_limit_key'),
        call.exception('Redis error performing delete on delete_key'),
        call.exception('Redis error performing delete on a, b, c'),
    ]

def test_should_raise_exception_if_raise_set_to_true(app):
    app.config['REDIS_ENABLED'] = True
    redis_client = RedisClient()
    redis_client.init_app(app)
    redis_client.redis_store.get = Mock(side_effect=Exception('get failed'))
    redis_client.redis_store.set = Mock(side_effect=Exception('set failed'))
    redis_client.redis_store.incr = Mock(side_effect=Exception('inc failed'))
    redis_client.redis_store.pipeline = Mock(side_effect=Exception('pipeline failed'))
    redis_client.redis_store.delete = Mock(side_effect=Exception('delete failed'))
    with pytest.raises(Exception) as e:
        redis_client.get('test', raise_exception=True)
    assert str(e.value) == 'get failed'
    with pytest.raises(Exception) as e:
        redis_client.set('test', 'test', raise_exception=True)
    assert str(e.value) == 'set failed'
    with pytest.raises(Exception) as e:
        redis_client.incr('test', raise_exception=True)
    assert str(e.value) == 'inc failed'
    with pytest.raises(Exception) as e:
        redis_client.exceeded_rate_limit('test', 100, 200, raise_exception=True)
    assert str(e.value) == 'pipeline failed'
    with pytest.raises(Exception) as e:
        redis_client.delete('test', raise_exception=True)
    assert str(e.value) == 'delete failed'

def test_should_not_call_set_if_not_enabled(mocked_redis_client):
    mocked_redis_client.active = False
    assert not mocked_redis_client.set('key', 'value')
    mocked_redis_client.redis_store.set.assert_not_called()

def test_should_call_set_if_enabled(mocked_redis_client):
    mocked_redis_client.set('key', 'value')
    mocked_redis_client.redis_store.set.assert_called_with('key', 'value', None, None, False, False)

def test_should_not_call_get_if_not_enabled(mocked_redis_client):
    mocked_redis_client.active = False
    mocked_redis_client.get('key')
    mocked_redis_client.redis_store.get.assert_not_called()

def test_should_not_call_redis_if_not_enabled_for_rate_limit_check(mocked_redis_client):
    mocked_redis_client.active = False
    mocked_redis_client.exceeded_rate_limit('key', 100, 200)
    mocked_redis_client.redis_store.pipeline.assert_not_called()

def test_should_call_get_if_enabled(mocked_redis_client):
    assert mocked_redis_client.get('key') == 100
    mocked_redis_client.redis_store.get.assert_called_with('key')

def test_should_build_cache_key_service_and_action(sample_service):
    with freeze_time("2016-01-01 12:00:00.000000"):
        assert daily_limit_cache_key(sample_service.id) == '{}-2016-01-01-count'.format(sample_service.id)

def test_should_build_daily_limit_cache_key(sample_service):
    assert rate_limit_cache_key(sample_service.id, 'TEST') == '{}-TEST'.format(sample_service.id)

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_add_correct_calls_to_the_pipe(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_client.exceeded_rate_limit("key", 100, 100)
    assert mocked_redis_client.redis_store.pipeline.called
    mocked_redis_pipeline.zadd.assert_called_with("key", {978350400.0: 978350400.0})
    mocked_redis_pipeline.zremrangebyscore.assert_called_with("key", '-inf', 978350300.0)
    mocked_redis_pipeline.zcard.assert_called_with("key")
    mocked_redis_pipeline.expire.assert_called_with("key", 100)
    assert mocked_redis_pipeline.execute.called

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_fail_request_if_over_limit(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 100, True]
    assert mocked_redis_client.exceeded_rate_limit("key", 99, 100)

@freeze_time("2001-01-01 12:00:00.000000")
def test_should_allow_request_if_not_over_limit(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 100, True]
    assert not mocked_redis_client.exceeded_rate_limit("key", 101, 100)

@freeze_time("2001-01-01 12:00:00.000000")
def test_rate_limit_not_exceeded(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_pipeline.execute.return_value = [True, True, 80, True]
    assert not mocked_redis_client.exceeded_rate_limit("key", 90, 100)

def test_should_not_call_rate_limit_if_not_enabled(mocked_redis_client, mocked_redis_pipeline):
    mocked_redis_client.active = False

    assert not mocked_redis_client.exceeded_rate_limit('key', 100, 100)
    assert not mocked_redis_client.redis_store.pipeline.called

def test_delete(mocked_redis_client):
    key = 'hash-key'
    mocked_redis_client.delete(key)
    mocked_redis_client.redis_store.delete.assert_called_with(key)

def test_multi_delete(mocked_redis_client):
    mocked_redis_client.delete('a', 'b', 'c')
    mocked_redis_client.redis_store.delete.assert_called_with('a', 'b', 'c')

@pytest.mark.parametrize('input,output', [
    (b'asdf', b'asdf'),
    ('asdf', 'asdf'),
    (0, 0),
    (1.2, 1.2),
    (uuid.UUID(int=0), '00000000-0000-0000-0000-000000000000'),
    pytest.param({'a': 1}, None, marks=pytest.mark.xfail(raises=ValueError)),
    pytest.param(datetime.utcnow(), None, marks=pytest.mark.xfail(raises=ValueError)),
])
def test_prepare_value(input, output):
    assert prepare_value(input) == output

def test_delete_cache_keys(mocked_redis_client):
    delete_mock = Mock(return_value=4)
    mocked_redis_client.scripts = {'delete-keys-by-pattern': delete_mock}

    ret = mocked_redis_client.delete_cache_keys_by_pattern('foo')

    assert ret == 4
    delete_mock.assert_called_once_with(args=['foo'])

def test_delete_cache_keys_returns_zero_when_redis_disabled(mocked_redis_client):
    mocked_redis_client.active = False
    delete_mock = Mock()
    mocked_redis_client.scripts = {'delete-keys-by-pattern': delete_mock}

    ret = mocked_redis_client.delete_cache_keys_by_pattern('foo')

    assert delete_mock.called is False
    assert ret == 0
<|endoftext|>


<commit_before># coding: utf8
# Author: Rodrigo Bistolfi
# Date: 03/2013

""" Test cases for Nikola ReST extensions.
A base class ReSTExtensionTestCase provides the tests basic behaivor.
Subclasses must override the "sample" class attribute with the ReST markup.
The sample will be rendered as HTML using publish_parts() by setUp().
One method is provided for checking the resulting HTML:

    * assertHTMLContains(element, attributes=None, text=None)

The HTML is parsed with lxml for checking against the data you provide. The
method takes an element argument, a string representing the *name* of an HTML
tag, like "script" or "iframe". We will try to find this tag in the document
and perform the tests on it. You can pass a dictionary to the attributes kwarg
representing the name and the value of the tag attributes. The text kwarg takes
a string argument, which will be tested against the contents of the HTML
element.
One last caveat: you need to url unquote your urls if you are going to test
attributes like "src" or "link", since the HTML rendered by docutils will be
always unquoted.

"""

from __future__ import unicode_literals, absolute_import

import codecs
try:
    from io import StringIO
except ImportError:
    from StringIO import StringIO  # NOQA
import os
import sys
import tempfile

import docutils
from lxml import html
from nose.plugins.skip import SkipTest
import unittest
from yapsy.PluginManager import PluginManager

from nikola import utils
import nikola.plugins.compile.rest
from nikola.plugins.compile.rest import gist
from nikola.plugins.compile.rest import vimeo
import nikola.plugins.compile.rest.listing
from nikola.plugins.compile.rest.doc import Plugin as DocPlugin
from nikola.utils import _reload
from nikola.plugin_categories import (
    Command,
    Task,
    LateTask,
    TemplateSystem,
    PageCompiler,
    TaskMultiplier,
    RestExtension,
)
from .base import BaseTestCase

class FakePost(object):

    def __init__(self, title, slug):
        self._title = title
        self._slug = slug
        self._meta = {'slug': slug}

    def title(self):
        return self._title

    def meta(self, key):
        return self._meta[key]

    def permalink(self):
        return '/posts/' + self._slug

class FakeSite(object):
    def __init__(self):
        self.template_system = self
        self.config = {
            'DISABLED_PLUGINS': [],
            'EXTRA_PLUGINS': [],
            'DEFAULT_LANG': 'en',
            'LOGGING_HANDLERS': {'stderr': {'loglevel': 'WARNING', 'bubble': True}}
        }
        self.EXTRA_PLUGINS = self.config['EXTRA_PLUGINS']
        self.plugin_manager = PluginManager(categories_filter={
            "Command": Command,
            "Task": Task,
            "LateTask": LateTask,
            "TemplateSystem": TemplateSystem,
            "PageCompiler": PageCompiler,
            "TaskMultiplier": TaskMultiplier,
            "RestExtension": RestExtension,
        })
        self.plugin_manager.setPluginInfoExtension('plugin')
        if sys.version_info[0] == 3:
            places = [
                os.path.join(os.path.dirname(utils.__file__), 'plugins'),
            ]
        else:
            places = [
                os.path.join(os.path.dirname(utils.__file__), utils.sys_encode('plugins')),
            ]
        self.plugin_manager.setPluginPlaces(places)
        self.plugin_manager.collectPlugins()

        self.timeline = [
            FakePost(title='Fake post',
                     slug='fake-post')
        ]

    def render_template(self, name, _, context):
        return('')

class ReSTExtensionTestCase(BaseTestCase):
    """ Base class for testing ReST extensions """

    sample = 'foo'
    deps = None

    def setUp(self):
        self.compiler = nikola.plugins.compile.rest.CompileRest()
        self.compiler.set_site(FakeSite())
        return super(ReSTExtensionTestCase, self).setUp()

    def basic_test(self):
        """ Parse cls.sample into a HTML document tree """
        self.setHtmlFromRst(self.sample)

    def setHtmlFromRst(self, rst):
        """ Create html output from rst string """
        tmpdir = tempfile.mkdtemp()
        inf = os.path.join(tmpdir, 'inf')
        outf = os.path.join(tmpdir, 'outf')
        depf = os.path.join(tmpdir, 'outf.dep')
        with codecs.open(inf, 'wb+', 'utf8') as f:
            f.write(rst)
        self.html = self.compiler.compile_html(inf, outf)
        with codecs.open(outf, 'r', 'utf8') as f:
            self.html = f.read()
        os.unlink(inf)
        os.unlink(outf)
        if os.path.isfile(depf):
            with codecs.open(depf, 'r', 'utf8') as f:
                self.assertEqual(self.deps, f.read())
            os.unlink(depf)
        else:
            self.assertEqual(self.deps, None)
        os.rmdir(tmpdir)
        self.html_doc = html.parse(StringIO(self.html))

    def assertHTMLContains(self, element, attributes=None, text=None):
        """ Test if HTML document includes an element with the given
        attributes and text content

        """
        try:
            tag = next(self.html_doc.iter(element))
        except StopIteration:
            raise Exception("<{0}> not in {1}".format(element, self.html))
        else:
            if attributes:
                arg_attrs = set(attributes.items())
                tag_attrs = set(tag.items())
                self.assertTrue(arg_attrs.issubset(tag_attrs))
            if text:
                self.assertIn(text, tag.text)

class ReSTExtensionTestCaseTestCase(ReSTExtensionTestCase):
    """ Simple test for our base class :) """

    sample = '.. raw:: html\n\n   spam'

    def test_test(self):
        self.basic_test()
        self.assertHTMLContains("iframe", attributes={"src": "foo"},
                                text="spam")
        self.assertRaises(Exception, self.assertHTMLContains, "eggs", {})

class MathTestCase(ReSTExtensionTestCase):
    sample = ':math:`e^{ix} = \cos x + i\sin x`'

    def test_mathjax(self):
        """ Test that math is outputting MathJax."""
        self.basic_test()
        self.assertHTMLContains("span", attributes={"class": "math"},
                                text="\(e^{ix} = \cos x + i\sin x\)")

class GistTestCase(ReSTExtensionTestCase):
    """ Test GitHubGist.
    We will replace get_raw_gist() and get_raw_gist_with_filename()
    monkeypatching the GitHubGist class for avoiding network dependency

    """
    gist_type = gist.GitHubGist
    sample = '.. gist:: fake_id\n   :file: spam.py'
    sample_without_filename = '.. gist:: fake_id2'

    def setUp(self):
        """ Patch GitHubGist for avoiding network dependency """
        super(GistTestCase, self).setUp()
        self.gist_type.get_raw_gist_with_filename = lambda *_: 'raw_gist_file'
        self.gist_type.get_raw_gist = lambda *_: "raw_gist"
        _reload(nikola.plugins.compile.rest)

    def test_gist(self):
        """ Test the gist directive with filename """
        raise SkipTest
        self.setHtmlFromRst(self.sample)
        output = 'https://gist.github.com/fake_id.js?file=spam.py'
        self.assertHTMLContains("script", attributes={"src": output})
        self.assertHTMLContains("pre", text="raw_gist_file")

    def test_gist_without_filename(self):
        """ Test the gist directive without filename """
        raise SkipTest
        self.setHtmlFromRst(self.sample_without_filename)
        output = 'https://gist.github.com/fake_id2.js'
        self.assertHTMLContains("script", attributes={"src": output})
        self.assertHTMLContains("pre", text="raw_gist")

class GistIntegrationTestCase(ReSTExtensionTestCase):
    """ Test requests integration. The gist plugin uses requests to fetch gist
    contents and place it in a noscript tag.

    """
    sample = '.. gist:: 1812835'

    def test_gist_integration(self):
        """ Fetch contents of the gist from GH and render in a noscript tag """
        self.basic_test()
        text = ('Be alone, that is the secret of invention: be alone, that is'
                ' when ideas are born. -- Nikola Tesla')
        self.assertHTMLContains('pre', text=text)

class SlidesTestCase(ReSTExtensionTestCase):
    """ Slides test case """

    sample = '.. slides:: IMG.jpg\n'

    def test_slides(self):
        """ Test the slides js generation and img tag creation """
        self.basic_test()
        self.assertHTMLContains("img", attributes={"src": "IMG.jpg"})

class SoundCloudTestCase(ReSTExtensionTestCase):
    """ SoundCloud test case """

    sample = '.. soundcloud:: SID\n   :height: 400\n   :width: 600'

    def test_soundcloud(self):
        """ Test SoundCloud iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("https://w.soundcloud.com"
                                                    "/player/?url=http://"
                                                    "api.soundcloud.com/"
                                                    "tracks/SID"),
                                            "height": "400", "width": "600"})

class VimeoTestCase(ReSTExtensionTestCase):
    """Vimeo test.
    Set Vimeo.request_size to False for avoiding querying the Vimeo api
    over the network

    """
    sample = '.. vimeo:: VID\n   :height: 400\n   :width: 600'

    def setUp(self):
        """ Disable query of the vimeo api over the wire """
        vimeo.Vimeo.request_size = False
        super(VimeoTestCase, self).setUp()
        _reload(nikola.plugins.compile.rest)

    def test_vimeo(self):
        """ Test Vimeo iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("http://player.vimeo.com/"
                                                    "video/VID"),
                                            "height": "400", "width": "600"})

class YoutubeTestCase(ReSTExtensionTestCase):
    """ Youtube test case """

    sample = '.. youtube:: YID\n   :height: 400\n   :width: 600'

    def test_youtube(self):
        """ Test Youtube iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("http://www.youtube.com/"
                                                    "embed/YID?rel=0&hd=1&"
                                                    "wmode=transparent"),
                                            "height": "400", "width": "600"})

class ListingTestCase(ReSTExtensionTestCase):
    """ Listing test case and CodeBlock alias tests """

    deps = None
    sample1 = '.. listing:: nikola.py python\n\n'
    sample2 = '.. code-block:: python\n\n   import antigravity'
    sample3 = '.. sourcecode:: python\n\n   import antigravity'

    #def test_listing(self):
        ##""" Test that we can render a file object contents without errors """
        ##with cd(os.path.dirname(__file__)):
            #self.deps = 'listings/nikola.py'
            #self.setHtmlFromRst(self.sample1)

    def test_codeblock_alias(self):
        """ Test CodeBlock aliases """
        self.deps = None
        self.setHtmlFromRst(self.sample2)
        self.setHtmlFromRst(self.sample3)

class DocTestCase(ReSTExtensionTestCase):
    """ Ref role test case """

    sample = 'Sample for testing my :doc:`doesnt-exist-post`'
    sample1 = 'Sample for testing my :doc:`fake-post`'
    sample2 = 'Sample for testing my :doc:`titled post <fake-post>`'

    def setUp(self):
        # Initialize plugin, register role
        self.plugin = DocPlugin()
        self.plugin.set_site(FakeSite())
        # Hack to fix leaked state from integration tests
        try:
            f = docutils.parsers.rst.roles.role('doc', None, None, None)[0]
            f.site = FakeSite()
        except AttributeError:
            pass
        return super(DocTestCase, self).setUp()

    def test_doc_doesnt_exist(self):
        self.assertRaises(Exception, self.assertHTMLContains, 'anything', {})

    def test_doc(self):
        self.setHtmlFromRst(self.sample1)
        self.assertHTMLContains('a',
                                text='Fake post',
                                attributes={'href': '/posts/fake-post'})

    def test_doc_titled(self):
        self.setHtmlFromRst(self.sample2)
        self.assertHTMLContains('a',
                                text='titled post',
                                attributes={'href': '/posts/fake-post'})

if __name__ == "__main__":
    unittest.main()
<commit_msg>Add logging handler so longhandler plugins don't need ot be triggered.<commit_after># coding: utf8
# Author: Rodrigo Bistolfi
# Date: 03/2013

""" Test cases for Nikola ReST extensions.
A base class ReSTExtensionTestCase provides the tests basic behaivor.
Subclasses must override the "sample" class attribute with the ReST markup.
The sample will be rendered as HTML using publish_parts() by setUp().
One method is provided for checking the resulting HTML:

    * assertHTMLContains(element, attributes=None, text=None)

The HTML is parsed with lxml for checking against the data you provide. The
method takes an element argument, a string representing the *name* of an HTML
tag, like "script" or "iframe". We will try to find this tag in the document
and perform the tests on it. You can pass a dictionary to the attributes kwarg
representing the name and the value of the tag attributes. The text kwarg takes
a string argument, which will be tested against the contents of the HTML
element.
One last caveat: you need to url unquote your urls if you are going to test
attributes like "src" or "link", since the HTML rendered by docutils will be
always unquoted.

"""

from __future__ import unicode_literals, absolute_import

import codecs
try:
    from io import StringIO
except ImportError:
    from StringIO import StringIO  # NOQA
import os
import sys
import tempfile

import docutils
from lxml import html
from nose.plugins.skip import SkipTest
import unittest
from yapsy.PluginManager import PluginManager

from nikola import utils
import nikola.plugins.compile.rest
from nikola.plugins.compile.rest import gist
from nikola.plugins.compile.rest import vimeo
import nikola.plugins.compile.rest.listing
from nikola.plugins.compile.rest.doc import Plugin as DocPlugin
from nikola.utils import _reload, STDERR_HANDLER
from nikola.plugin_categories import (
    Command,
    Task,
    LateTask,
    TemplateSystem,
    PageCompiler,
    TaskMultiplier,
    RestExtension,
)
from .base import BaseTestCase

class FakePost(object):

    def __init__(self, title, slug):
        self._title = title
        self._slug = slug
        self._meta = {'slug': slug}

    def title(self):
        return self._title

    def meta(self, key):
        return self._meta[key]

    def permalink(self):
        return '/posts/' + self._slug

class FakeSite(object):
    def __init__(self):
        self.template_system = self
        self.config = {
            'DISABLED_PLUGINS': [],
            'EXTRA_PLUGINS': [],
            'DEFAULT_LANG': 'en',
        }
        self.EXTRA_PLUGINS = self.config['EXTRA_PLUGINS']
        self.plugin_manager = PluginManager(categories_filter={
            "Command": Command,
            "Task": Task,
            "LateTask": LateTask,
            "TemplateSystem": TemplateSystem,
            "PageCompiler": PageCompiler,
            "TaskMultiplier": TaskMultiplier,
            "RestExtension": RestExtension,
        })
        self.loghandlers = [STDERR_HANDLER]
        self.plugin_manager.setPluginInfoExtension('plugin')
        if sys.version_info[0] == 3:
            places = [
                os.path.join(os.path.dirname(utils.__file__), 'plugins'),
            ]
        else:
            places = [
                os.path.join(os.path.dirname(utils.__file__), utils.sys_encode('plugins')),
            ]
        self.plugin_manager.setPluginPlaces(places)
        self.plugin_manager.collectPlugins()

        self.timeline = [
            FakePost(title='Fake post',
                     slug='fake-post')
        ]

    def render_template(self, name, _, context):
        return('')

class ReSTExtensionTestCase(BaseTestCase):
    """ Base class for testing ReST extensions """

    sample = 'foo'
    deps = None

    def setUp(self):
        self.compiler = nikola.plugins.compile.rest.CompileRest()
        self.compiler.set_site(FakeSite())
        return super(ReSTExtensionTestCase, self).setUp()

    def basic_test(self):
        """ Parse cls.sample into a HTML document tree """
        self.setHtmlFromRst(self.sample)

    def setHtmlFromRst(self, rst):
        """ Create html output from rst string """
        tmpdir = tempfile.mkdtemp()
        inf = os.path.join(tmpdir, 'inf')
        outf = os.path.join(tmpdir, 'outf')
        depf = os.path.join(tmpdir, 'outf.dep')
        with codecs.open(inf, 'wb+', 'utf8') as f:
            f.write(rst)
        self.html = self.compiler.compile_html(inf, outf)
        with codecs.open(outf, 'r', 'utf8') as f:
            self.html = f.read()
        os.unlink(inf)
        os.unlink(outf)
        if os.path.isfile(depf):
            with codecs.open(depf, 'r', 'utf8') as f:
                self.assertEqual(self.deps, f.read())
            os.unlink(depf)
        else:
            self.assertEqual(self.deps, None)
        os.rmdir(tmpdir)
        self.html_doc = html.parse(StringIO(self.html))

    def assertHTMLContains(self, element, attributes=None, text=None):
        """ Test if HTML document includes an element with the given
        attributes and text content

        """
        try:
            tag = next(self.html_doc.iter(element))
        except StopIteration:
            raise Exception("<{0}> not in {1}".format(element, self.html))
        else:
            if attributes:
                arg_attrs = set(attributes.items())
                tag_attrs = set(tag.items())
                self.assertTrue(arg_attrs.issubset(tag_attrs))
            if text:
                self.assertIn(text, tag.text)

class ReSTExtensionTestCaseTestCase(ReSTExtensionTestCase):
    """ Simple test for our base class :) """

    sample = '.. raw:: html\n\n   spam'

    def test_test(self):
        self.basic_test()
        self.assertHTMLContains("iframe", attributes={"src": "foo"},
                                text="spam")
        self.assertRaises(Exception, self.assertHTMLContains, "eggs", {})

class MathTestCase(ReSTExtensionTestCase):
    sample = ':math:`e^{ix} = \cos x + i\sin x`'

    def test_mathjax(self):
        """ Test that math is outputting MathJax."""
        self.basic_test()
        self.assertHTMLContains("span", attributes={"class": "math"},
                                text="\(e^{ix} = \cos x + i\sin x\)")

class GistTestCase(ReSTExtensionTestCase):
    """ Test GitHubGist.
    We will replace get_raw_gist() and get_raw_gist_with_filename()
    monkeypatching the GitHubGist class for avoiding network dependency

    """
    gist_type = gist.GitHubGist
    sample = '.. gist:: fake_id\n   :file: spam.py'
    sample_without_filename = '.. gist:: fake_id2'

    def setUp(self):
        """ Patch GitHubGist for avoiding network dependency """
        super(GistTestCase, self).setUp()
        self.gist_type.get_raw_gist_with_filename = lambda *_: 'raw_gist_file'
        self.gist_type.get_raw_gist = lambda *_: "raw_gist"
        _reload(nikola.plugins.compile.rest)

    def test_gist(self):
        """ Test the gist directive with filename """
        raise SkipTest
        self.setHtmlFromRst(self.sample)
        output = 'https://gist.github.com/fake_id.js?file=spam.py'
        self.assertHTMLContains("script", attributes={"src": output})
        self.assertHTMLContains("pre", text="raw_gist_file")

    def test_gist_without_filename(self):
        """ Test the gist directive without filename """
        raise SkipTest
        self.setHtmlFromRst(self.sample_without_filename)
        output = 'https://gist.github.com/fake_id2.js'
        self.assertHTMLContains("script", attributes={"src": output})
        self.assertHTMLContains("pre", text="raw_gist")

class GistIntegrationTestCase(ReSTExtensionTestCase):
    """ Test requests integration. The gist plugin uses requests to fetch gist
    contents and place it in a noscript tag.

    """
    sample = '.. gist:: 1812835'

    def test_gist_integration(self):
        """ Fetch contents of the gist from GH and render in a noscript tag """
        self.basic_test()
        text = ('Be alone, that is the secret of invention: be alone, that is'
                ' when ideas are born. -- Nikola Tesla')
        self.assertHTMLContains('pre', text=text)

class SlidesTestCase(ReSTExtensionTestCase):
    """ Slides test case """

    sample = '.. slides:: IMG.jpg\n'

    def test_slides(self):
        """ Test the slides js generation and img tag creation """
        self.basic_test()
        self.assertHTMLContains("img", attributes={"src": "IMG.jpg"})

class SoundCloudTestCase(ReSTExtensionTestCase):
    """ SoundCloud test case """

    sample = '.. soundcloud:: SID\n   :height: 400\n   :width: 600'

    def test_soundcloud(self):
        """ Test SoundCloud iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("https://w.soundcloud.com"
                                                    "/player/?url=http://"
                                                    "api.soundcloud.com/"
                                                    "tracks/SID"),
                                            "height": "400", "width": "600"})

class VimeoTestCase(ReSTExtensionTestCase):
    """Vimeo test.
    Set Vimeo.request_size to False for avoiding querying the Vimeo api
    over the network

    """
    sample = '.. vimeo:: VID\n   :height: 400\n   :width: 600'

    def setUp(self):
        """ Disable query of the vimeo api over the wire """
        vimeo.Vimeo.request_size = False
        super(VimeoTestCase, self).setUp()
        _reload(nikola.plugins.compile.rest)

    def test_vimeo(self):
        """ Test Vimeo iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("http://player.vimeo.com/"
                                                    "video/VID"),
                                            "height": "400", "width": "600"})

class YoutubeTestCase(ReSTExtensionTestCase):
    """ Youtube test case """

    sample = '.. youtube:: YID\n   :height: 400\n   :width: 600'

    def test_youtube(self):
        """ Test Youtube iframe tag generation """
        self.basic_test()
        self.assertHTMLContains("iframe",
                                attributes={"src": ("http://www.youtube.com/"
                                                    "embed/YID?rel=0&hd=1&"
                                                    "wmode=transparent"),
                                            "height": "400", "width": "600"})

class ListingTestCase(ReSTExtensionTestCase):
    """ Listing test case and CodeBlock alias tests """

    deps = None
    sample1 = '.. listing:: nikola.py python\n\n'
    sample2 = '.. code-block:: python\n\n   import antigravity'
    sample3 = '.. sourcecode:: python\n\n   import antigravity'

    #def test_listing(self):
        ##""" Test that we can render a file object contents without errors """
        ##with cd(os.path.dirname(__file__)):
            #self.deps = 'listings/nikola.py'
            #self.setHtmlFromRst(self.sample1)

    def test_codeblock_alias(self):
        """ Test CodeBlock aliases """
        self.deps = None
        self.setHtmlFromRst(self.sample2)
        self.setHtmlFromRst(self.sample3)

class DocTestCase(ReSTExtensionTestCase):
    """ Ref role test case """

    sample = 'Sample for testing my :doc:`doesnt-exist-post`'
    sample1 = 'Sample for testing my :doc:`fake-post`'
    sample2 = 'Sample for testing my :doc:`titled post <fake-post>`'

    def setUp(self):
        # Initialize plugin, register role
        self.plugin = DocPlugin()
        self.plugin.set_site(FakeSite())
        # Hack to fix leaked state from integration tests
        try:
            f = docutils.parsers.rst.roles.role('doc', None, None, None)[0]
            f.site = FakeSite()
        except AttributeError:
            pass
        return super(DocTestCase, self).setUp()

    def test_doc_doesnt_exist(self):
        self.assertRaises(Exception, self.assertHTMLContains, 'anything', {})

    def test_doc(self):
        self.setHtmlFromRst(self.sample1)
        self.assertHTMLContains('a',
                                text='Fake post',
                                attributes={'href': '/posts/fake-post'})

    def test_doc_titled(self):
        self.setHtmlFromRst(self.sample2)
        self.assertHTMLContains('a',
                                text='titled post',
                                attributes={'href': '/posts/fake-post'})

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


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

"""
test_stockfighter
----------------------------------

Tests for `stockfighter` module.
"""
import os
import pytest
from stockfighter.stockfighter import Stockfighter

@pytest.fixture
def client():
    return Stockfighter(
        venue='TESTEX',
        account='EXB123456',
    )
STOCK = 'FOOBAR'

def test_heartbeat(client):
    assert client.heartbeat() is True

def test_venue_healthcheck(client):
    assert client.venue_healthcheck() is True

def test_venue_stocks(client):
    assert client.venue_stocks()

def test_orderbook_for_stock(client):
    assert client.orderbook_for_stock(STOCK)

def test_place_new_order(client):
    assert client.place_new_order(
        stock=STOCK,
        price=500,  # Ignored for this market type
        qty=10,
        direction='buy',
        order_type='market',
    )

def test_quote_for_stock(client):
    assert client.quote_for_stock(stock=STOCK)
<commit_msg>Test README quickstart<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
test_stockfighter
----------------------------------

Tests for `stockfighter` module.
"""
import os
import pytest
from stockfighter.stockfighter import Stockfighter

@pytest.fixture
def client():
    return Stockfighter(
        venue='TESTEX',
        account='EXB123456',
    )
STOCK = 'FOOBAR'

def test_heartbeat(client):
    assert client.heartbeat() is True

def test_venue_healthcheck(client):
    assert client.venue_healthcheck() is True

def test_venue_stocks(client):
    assert client.venue_stocks()

def test_orderbook_for_stock(client):
    assert client.orderbook_for_stock(STOCK)

def test_place_new_order(client):
    assert client.place_new_order(
        stock=STOCK,
        price=500,  # Ignored for this market type
        qty=10,
        direction='buy',
        order_type='market',
    )

def test_quote_for_stock(client):
    assert client.quote_for_stock(stock=STOCK)

def test_readme():
    """Test the content of the README works as advertised."""
    from stockfighter import Stockfighter
    s = Stockfighter(venue='TESTEX', account='EXB123456')
    print s.venue_stocks()
<|endoftext|>


<commit_before>import random
from config import MEDIA_LOCAL_DIR
from config import MEDIA_WEB_DIR
import tts_provider

random_code = random.randint(0, 1000000000)
tts_web_path = '%s%s_%s.mp3' % (MEDIA_WEB_DIR, 'en', 'test')
tts_local_path = '%s%s_%s.mp3' % (MEDIA_LOCAL_DIR, 'en', 'test')
print tts_local_path
print tts_web_path
tts_provider.google('en', "Senators meeting on Obama nominees ends without deal", tts_local_path)
<commit_msg>updated constant var names<commit_after>import random
from config import MEDIA_LOCAL_DIR
from config import MEDIA_PUBLIC_DIR
import tts_provider

random_code = random.randint(0, 1000000000)
tts_web_path = '%s%s_%s.mp3' % (MEDIA_PUBLIC_DIR, 'en', 'test')
tts_local_path = '%s%s_%s.mp3' % (MEDIA_LOCAL_DIR, 'en', 'test')
print tts_local_path
print tts_web_path
tts_provider.google('en', "Senators meeting on Obama nominees ends without deal", tts_local_path)
<|endoftext|>


<commit_before>import pytest
from mock import MagicMock

from user_sync.engine.umapi import UmapiTargetInfo, UmapiConnectors, RuleProcessor
from user_sync.connector.connector_umapi import Commands

@pytest.fixture
def rule_processor():
    return RuleProcessor({})

@pytest.fixture()
def mock_umapi_connectors():
    def _mock_umapi_connectors(*args):
        return UmapiConnectors(
            MockUmapiConnector(),
            {a: MockUmapiConnector(name=a) for a in args})

    return _mock_umapi_connectors

@pytest.fixture()
def mock_umapi_info():
    def _mock_umapi_info(name=None, groups=[]):
        mock_umapi_info = UmapiTargetInfo(name)
        for g in groups:
            mock_umapi_info.add_mapped_group(g)
        return mock_umapi_info

    return _mock_umapi_info

class MockUmapiConnector(MagicMock):
    class MockActionManager:
        def get_statistics(self):
            return 10, 2

    def __init__(self, name='', options={}, *args, **kwargs):
        super(MockUmapiConnector, self).__init__(*args, **kwargs)
        self.name = 'umapi' + name
        self.trusted = False
        self.options = options
        self.action_manager = MockUmapiConnector.MockActionManager()
        self.commands_sent = None
        self.users = {}

    def send_commands(self, commands):
        self.commands_sent = commands

    def get_action_manager(self):
        return self.action_manager

    def iter_users(self):
        return self.users

    def test_create_umapi_user(self, rule_processor, mock_dir_user, mock_umapi_info):
        user = mock_dir_user
        rp = rule_processor

        key = rp.get_user_key(user['identity_type'], user['username'], user['domain'])
        rp.directory_user_by_user_key[key] = user
        rp.options['process_groups'] = True
        rp.push_umapi = True

        groups_to_add = {'Group A', 'Group C'}
        info = mock_umapi_info(None, {'Group A', 'Group B'})
        conn = MockUmapiConnector()
        rp.create_umapi_user(key, groups_to_add, info, conn)

        result = vars(conn.commands_sent)['do_list']
        result[0][1].pop('on_conflict')
        assert result[0] == ('create', {
            'email': user['email'],
            'first_name': user['firstname'],
            'last_name': user['lastname'],
            'country': user['country']})
        assert result[1] == ('remove_from_groups', {
            'groups': {'group b', 'group a'}})
        assert result[2] == ('add_to_groups', {
            'groups': {'Group C', 'Group A'}})

    def test_update_umapi_user(self, rule_processor, mock_dir_user, mock_umapi_user, get_mock_user_list):
        rp = rule_processor
        user = mock_dir_user
        mock_umapi_user['email'] = user['email']
        mock_umapi_user['username'] = user['username']
        mock_umapi_user['domain'] = user['domain']
        mock_umapi_user['type'] = user['identity_type']

        def update(up_user, up_attrs):
            group_add = set()
            group_rem = set()
            conn = MockUmapiConnector()
            info = UmapiTargetInfo(None)
            user_key = rp.get_user_key(up_user['identity_type'], up_user['username'], up_user['domain'])
            rp.directory_user_by_user_key[user_key] = up_user
            rp.update_umapi_user(info, user_key, conn, up_attrs, group_add, group_rem, mock_umapi_user)
            assert user_key in rp.updated_user_keys
            return vars(conn.commands_sent)

        up_attrs = {
            'firstname': user['firstname'],
            'lastname': user['lastname']}

        result = update(user, up_attrs)
        assert result == {
            'identity_type': user['identity_type'],
            'email': user['email'],
            'username': user['username'],
            'domain': user['domain'],
            'do_list': [('update', {
                'first_name': user['firstname'],
                'last_name': user['lastname']})]}

        user['username'] = 'different@example.com'
        result = update(user, up_attrs)
        assert result['username'] == user['email']

        user['email'] = 'different@example.com'
        up_attrs = {
            'email': user['email']}
        result = update(user, up_attrs)

        assert result == {
            'identity_type': user['identity_type'],
            'email': user['email'],
            'username': user['username'],
            'domain': user['domain'],
            'do_list': [('update', {
                'email': 'different@example.com',
                'username': user['username']})]}

    def test_create_umapi_commands_for_directory_user(self, rule_processor, mock_dir_user):
        rp = rule_processor
        user = mock_dir_user

        def get_commands(user, update_option='ignoreIfAlreadyExists'):
            attributes = rp.get_user_attributes(user)
            attributes['country'] = user['country']
            attributes['option'] = update_option
            commands = Commands(user['identity_type'], user['email'], user['username'], user['domain'])
            commands.add_user(attributes)
            return commands

        # simple case
        commands = get_commands(user)
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test do_update
        commands = get_commands(user, 'updateIfAlreadyExists')
        result = rp.create_umapi_commands_for_directory_user(user, do_update=True)
        assert vars(result) == vars(commands)

        # test username format
        user['username'] = 'nosymbol'
        commands = get_commands(user)
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test username format
        user['username'] = 'different@example.com'
        commands = get_commands(user)
        commands.update_user({
            "email": user['email'],
            "username": user['username']})
        commands.username = user['email']
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test console trusted
        user['username'] = 'different@example.com'
        commands = get_commands(user)
        commands.username = user['email']
        result = rp.create_umapi_commands_for_directory_user(user, console_trusted=True)
        assert vars(result) == vars(commands)

        # Default Country Code as None and Id Type as federatedID. Country as None in user
        rp.options['default_country_code'] = None
        user['country'] = None
        result = rp.create_umapi_commands_for_directory_user(user)
        assert result is None

        # Default Country Code as None with Id Type as enterpriseID. Country as None in user
        rp.options['default_country_code'] = None
        user['identity_type'] = 'enterpriseID'
        result = rp.create_umapi_commands_for_directory_user(user)
        user['country'] = 'UD'
        commands = get_commands(user)
        assert vars(result) == vars(commands)

        # Having Default Country Code with value 'US'. Country as None in user.
        rp.options['default_country_code'] = 'US'
        user['country'] = None
        result = rp.create_umapi_commands_for_directory_user(user)
        user['country'] = 'US'
        commands = get_commands(user)
        assert vars(result) == vars(commands)

        # Country as 'CA' in user
        user['country'] = 'CA'
        result = rp.create_umapi_commands_for_directory_user(user)
        commands = get_commands(user)
        assert vars(result) == vars(commands)

    def test_get_user_attribute_difference(self, rule_processor, mock_dir_user, mock_umapi_user):
        directory_user_mock_data = mock_dir_user
        umapi_users_mock_data = mock_umapi_user
        umapi_users_mock_data['firstname'] = 'Adobe'
        umapi_users_mock_data['lastname'] = 'Username'
        umapi_users_mock_data['email'] = 'adobe.username@example.com'

        expected = {
            'email': mock_dir_user['email'],
            'firstname': mock_dir_user['firstname'],
            'lastname': mock_dir_user['lastname']
        }

        assert expected == rule_processor.get_user_attribute_difference(
            directory_user_mock_data, umapi_users_mock_data)

        # test with no change
        assert rule_processor.get_user_attribute_difference(
            umapi_users_mock_data, umapi_users_mock_data) == {}<commit_msg>umapi tests cont <commit_after>import mock
import pytest
from mock import MagicMock

from user_sync.engine.umapi import UmapiTargetInfo, UmapiConnectors, RuleProcessor
from user_sync.connector.connector_umapi import Commands

@pytest.fixture
def rule_processor():
    return RuleProcessor({})

@pytest.fixture()
def mock_umapi_connectors():
    def _mock_umapi_connectors(*args):
        return UmapiConnectors(
            MockUmapiConnector(),
            {a: MockUmapiConnector(name=a) for a in args})

    return _mock_umapi_connectors

@pytest.fixture()
def mock_umapi_info():
    def _mock_umapi_info(name=None, groups=[]):
        mock_umapi_info = UmapiTargetInfo(name)
        for g in groups:
            mock_umapi_info.add_mapped_group(g)
        return mock_umapi_info

    return _mock_umapi_info

class MockUmapiConnector(MagicMock):
    class MockActionManager:
        def get_statistics(self):
            return 10, 2

    def __init__(self, name='', options={}, *args, **kwargs):
        super(MockUmapiConnector, self).__init__(*args, **kwargs)
        self.name = 'umapi' + name
        self.trusted = False
        self.options = options
        self.action_manager = MockUmapiConnector.MockActionManager()
        self.commands_sent = None
        self.users = {}

    def send_commands(self, commands):
        self.commands_sent = commands

    def get_action_manager(self):
        return self.action_manager

    def iter_users(self):
        return self.users

    def test_create_umapi_user(self, rule_processor, mock_dir_user, mock_umapi_info):
        user = mock_dir_user
        rp = rule_processor

        key = rp.get_user_key(user['identity_type'], user['username'], user['domain'])
        rp.directory_user_by_user_key[key] = user
        rp.options['process_groups'] = True
        rp.push_umapi = True

        groups_to_add = {'Group A', 'Group C'}
        info = mock_umapi_info(None, {'Group A', 'Group B'})
        conn = MockUmapiConnector()
        rp.create_umapi_user(key, groups_to_add, info, conn)

        result = vars(conn.commands_sent)['do_list']
        result[0][1].pop('on_conflict')
        assert result[0] == ('create', {
            'email': user['email'],
            'first_name': user['firstname'],
            'last_name': user['lastname'],
            'country': user['country']})
        assert result[1] == ('remove_from_groups', {
            'groups': {'group b', 'group a'}})
        assert result[2] == ('add_to_groups', {
            'groups': {'Group C', 'Group A'}})

    def test_update_umapi_user(self, rule_processor, mock_dir_user, mock_umapi_user, get_mock_user_list):
        rp = rule_processor
        user = mock_dir_user
        mock_umapi_user['email'] = user['email']
        mock_umapi_user['username'] = user['username']
        mock_umapi_user['domain'] = user['domain']
        mock_umapi_user['type'] = user['identity_type']

        def update(up_user, up_attrs):
            group_add = set()
            group_rem = set()
            conn = MockUmapiConnector()
            info = UmapiTargetInfo(None)
            user_key = rp.get_user_key(up_user['identity_type'], up_user['username'], up_user['domain'])
            rp.directory_user_by_user_key[user_key] = up_user
            rp.update_umapi_user(info, user_key, conn, up_attrs, group_add, group_rem, mock_umapi_user)
            assert user_key in rp.updated_user_keys
            return vars(conn.commands_sent)

        up_attrs = {
            'firstname': user['firstname'],
            'lastname': user['lastname']}

        result = update(user, up_attrs)
        assert result == {
            'identity_type': user['identity_type'],
            'email': user['email'],
            'username': user['username'],
            'domain': user['domain'],
            'do_list': [('update', {
                'first_name': user['firstname'],
                'last_name': user['lastname']})]}

        user['username'] = 'different@example.com'
        result = update(user, up_attrs)
        assert result['username'] == user['email']

        user['email'] = 'different@example.com'
        up_attrs = {
            'email': user['email']}
        result = update(user, up_attrs)

        assert result == {
            'identity_type': user['identity_type'],
            'email': user['email'],
            'username': user['username'],
            'domain': user['domain'],
            'do_list': [('update', {
                'email': 'different@example.com',
                'username': user['username']})]}

    def test_create_umapi_commands_for_directory_user(self, rule_processor, mock_dir_user):
        rp = rule_processor
        user = mock_dir_user

        def get_commands(user, update_option='ignoreIfAlreadyExists'):
            attributes = rp.get_user_attributes(user)
            attributes['country'] = user['country']
            attributes['option'] = update_option
            commands = Commands(user['identity_type'], user['email'], user['username'], user['domain'])
            commands.add_user(attributes)
            return commands

        # simple case
        commands = get_commands(user)
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test do_update
        commands = get_commands(user, 'updateIfAlreadyExists')
        result = rp.create_umapi_commands_for_directory_user(user, do_update=True)
        assert vars(result) == vars(commands)

        # test username format
        user['username'] = 'nosymbol'
        commands = get_commands(user)
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test username format
        user['username'] = 'different@example.com'
        commands = get_commands(user)
        commands.update_user({
            "email": user['email'],
            "username": user['username']})
        commands.username = user['email']
        result = rp.create_umapi_commands_for_directory_user(user)
        assert vars(result) == vars(commands)

        # test console trusted
        user['username'] = 'different@example.com'
        commands = get_commands(user)
        commands.username = user['email']
        result = rp.create_umapi_commands_for_directory_user(user, console_trusted=True)
        assert vars(result) == vars(commands)

        # Default Country Code as None and Id Type as federatedID. Country as None in user
        rp.options['default_country_code'] = None
        user['country'] = None
        result = rp.create_umapi_commands_for_directory_user(user)
        assert result is None

        # Default Country Code as None with Id Type as enterpriseID. Country as None in user
        rp.options['default_country_code'] = None
        user['identity_type'] = 'enterpriseID'
        result = rp.create_umapi_commands_for_directory_user(user)
        user['country'] = 'UD'
        commands = get_commands(user)
        assert vars(result) == vars(commands)

        # Having Default Country Code with value 'US'. Country as None in user.
        rp.options['default_country_code'] = 'US'
        user['country'] = None
        result = rp.create_umapi_commands_for_directory_user(user)
        user['country'] = 'US'
        commands = get_commands(user)
        assert vars(result) == vars(commands)

        # Country as 'CA' in user
        user['country'] = 'CA'
        result = rp.create_umapi_commands_for_directory_user(user)
        commands = get_commands(user)
        assert vars(result) == vars(commands)

    def test_get_user_attribute_difference(self, rule_processor, mock_dir_user, mock_umapi_user):
        directory_user_mock_data = mock_dir_user
        umapi_users_mock_data = mock_umapi_user
        umapi_users_mock_data['firstname'] = 'Adobe'
        umapi_users_mock_data['lastname'] = 'Username'
        umapi_users_mock_data['email'] = 'adobe.username@example.com'

        expected = {
            'email': mock_dir_user['email'],
            'firstname': mock_dir_user['firstname'],
            'lastname': mock_dir_user['lastname']
        }

        assert expected == rule_processor.get_user_attribute_difference(
            directory_user_mock_data, umapi_users_mock_data)

        # test with no change
        assert rule_processor.get_user_attribute_difference(
            umapi_users_mock_data, umapi_users_mock_data) == {}

    def test_get_directory_user_key(rule_processor):
        mock_directory_user_dict = {
            'email': 'exampledirectory@exmaple.com',
            'username': 'exampledirectory@example.com',
            'domain': 'example.com',
            'type': 'federatedID'
        }
        actual_result = rule_processor.get_directory_user_key(mock_directory_user_dict)
        assert actual_result == 'federatedID,7of9@example.com,'

    def test_get_umapi_user_key(rule_processor):
        mock_umapi_user_dict = {
            'email': '7of9@exmaple.com',
            'username': '7of9@example.com',
            'domain': 'example.com',
            'type': 'federatedID'
        }

        actual_result = rule_processor.get_umapi_user_key(mock_umapi_user_dict)
        assert actual_result == 'federatedID,7of9@example.com,'

    def test_get_user_key(rule_processor):
        key = rule_processor.get_user_key("federatedID", "wriker@example.com", "wriker@example.com", "example.com")
        assert key == 'federatedID,wriker@example.com,'

        key = rule_processor.get_user_key("federatedID", "wriker", "example.com")
        assert key == 'federatedID,wriker,example.com'

        assert not rule_processor.get_user_key(None, "wriker@example.com", "wriker@example.com", "example.com")
        assert not rule_processor.get_user_key("federatedID", None, "wriker@example.com")

    def test_parse_user_key(rule_processor):
        parsed_user_key = rule_processor.parse_user_key("federatedID,test_user@email.com,")
        assert parsed_user_key == ['federatedID', 'test_user@email.com', '']

        domain_parsed_key = rule_processor.parse_user_key("federatedID,test_user,email.com")
        assert domain_parsed_key == ['federatedID', 'test_user', 'email.com']

    def test_get_username_from_user_key(rule_processor):
        with mock.patch('user_sync.rules.RuleProcessor.parse_user_key') as parse:
            parse.return_value = ['federatedID', 'test_user@email.com', '']
            username = rule_processor.get_username_from_user_key("federatedID,test_user@email.com,")
            assert username == 'test_user@email.com'

    class TestUmapiTargetInfo():
        def test_add_mapped_group(self):
            umapi_target_info = UmapiTargetInfo("")
            umapi_target_info.add_mapped_group("All Students")
            assert "all students" in umapi_target_info.mapped_groups
            assert "All Students" in umapi_target_info.non_normalize_mapped_groups

        def test_add_additional_group(self):
            umapi_target_info = UmapiTargetInfo("")
            umapi_target_info.add_additional_group('old_name', 'new_name')
            assert umapi_target_info.additional_group_map['old_name'][0] == 'new_name'

        def test_add_desired_group_for(self):
            umapi_target_info = UmapiTargetInfo("")
            with mock.patch("user_sync.rules.UmapiTargetInfo.get_desired_groups") as mock_desired_groups:
                mock_desired_groups.return_valu
                e = None
                umapi_target_info.add_desired_group_for('user_key', 'group_name')
                assert umapi_target_info.desired_groups_by_user_key['user_key'] == {'group_name'}
<|endoftext|>