<commit_before>import re
import time
from unittest import mock
from unittest.mock import Mock, sentinel
from urllib.parse import urlparse

import os
from django.contrib.auth.models import User
from django.core.urlresolvers import resolve
from django.test.testcases import TestCase
from hamcrest import assert_that, contains_inanyorder, matches_regexp, match_equality
from requests import HTTPError

from osmaxx.api_client import ConversionApiClient, API_client
from osmaxx.excerptexport.models import Excerpt, ExtractionOrder, ExtractionOrderState, BBoxBoundingGeometry
from osmaxx.job_progress.views import tracker
from tests.test_helpers import vcr_explicit_path as vcr, absolute_cassette_lib_path


class ConversionApiClientAuthTestCase(TestCase):
    @vcr.use_cassette('fixtures/vcr/conversion_api-test_successful_login.yml')
    def test_successful_login(self):
        api_client = ConversionApiClient()

        self.assertIsNone(api_client.token)

        api_client._login()

        self.assertIsNotNone(api_client.token)

    @vcr.use_cassette('fixtures/vcr/conversion_api-test_failed_login.yml')
    def test_failed_login(self):
        api_client = ConversionApiClient()
        api_client.password = '<PASSWORD>'

        self.assertEqual(api_client.password, '<PASSWORD>')
        self.assertIsNone(api_client.token)

        expected_msg = \
            "400 Client Error: BAD REQUEST for url: http://localhost:8901/api/token-auth/"
        with self.assertRaisesRegex(HTTPError, "^{}$".format(re.escape(expected_msg))) as cm:
            api_client._login()

        self.assertEqual(
            API_client.reasons_for(cm.exception),
            {'non_field_errors': ['Unable to login with provided credentials.']}
        )
        self.assertIsNone(api_client.token)


class ConversionApiClientTestCase(TestCase):
    def setUp(self):
        self.request = Mock()
        self.request.build_absolute_uri.return_value = 'http://the-host.example.com/job_progress/tracker/1/'
        self.user = User.objects.create_user('user', '<EMAIL>', 'pw')
        self.bounding_box = BBoxBoundingGeometry.create_from_bounding_box_coordinates(
            40.77739734768811, 29.528980851173397, 40.77546776498174, 29.525547623634335
        )
        self.excerpt = Excerpt.objects.create(
            name='Neverland', is_active=True, is_public=True, owner=self.user, bounding_geometry=self.bounding_box
        )
        self.extraction_order = ExtractionOrder.objects.create(excerpt=self.excerpt, orderer=self.user)
        self.extraction_order.extraction_configuration = {
            'gis_formats': ['fgdb', 'spatialite'],
            'gis_options': {
                'coordinate_reference_system': 'WGS_84',
                'detail_level': 1
            }
        }
        self.api_client = ConversionApiClient()

    #
    # Unit tests:

    @mock.patch.object(ConversionApiClient, 'create_job', side_effect=[sentinel.job_1, sentinel.job_2])
    @mock.patch.object(
        ConversionApiClient, 'create_parametrization',
        create=True,  # TODO: remove 'create' once implemented
        side_effect=[sentinel.parametrization_1, sentinel.parametrization_2],
    )
    @mock.patch.object(ConversionApiClient, 'create_boundary', create=True)  # TODO: remove 'create' once implemented
    def test_extraction_order_forward_to_conversion_service(
            self, create_boundary_mock, create_parametrization_mock, create_job_mock):
        result = self.extraction_order.forward_to_conversion_service(incoming_request=self.request)

        create_boundary_mock.assert_called_once_with(self.bounding_box.geometry, name=self.excerpt.name)
        gis_conversion_options = self.extraction_order.extraction_configuration['gis_options']
        assert_that(
            create_parametrization_mock.mock_calls, contains_inanyorder(
                mock.call(create_boundary_mock.return_value, 'fgdb', gis_conversion_options),
                mock.call(create_boundary_mock.return_value, 'spatialite', gis_conversion_options),
            )
        )
        assert_that(
            create_job_mock.mock_calls, contains_inanyorder(
                mock.call(sentinel.parametrization_1, self.request),
                mock.call(sentinel.parametrization_2, self.request),
            )
        )
        assert_that(
            result, contains_inanyorder(
                sentinel.job_1,
                sentinel.job_2,
            )
        )

    #
    # Integration tests:
<commit_msg>ConversionApiClient.create_boundary exists now #406<commit_after>import re
import time
from unittest import mock
from unittest.mock import Mock, sentinel
from urllib.parse import urlparse

import os
from django.contrib.auth.models import User
from django.core.urlresolvers import resolve
from django.test.testcases import TestCase
from hamcrest import assert_that, contains_inanyorder, matches_regexp, match_equality
from requests import HTTPError

from osmaxx.api_client import ConversionApiClient, API_client
from osmaxx.excerptexport.models import Excerpt, ExtractionOrder, ExtractionOrderState, BBoxBoundingGeometry
from osmaxx.job_progress.views import tracker
from tests.test_helpers import vcr_explicit_path as vcr, absolute_cassette_lib_path


class ConversionApiClientAuthTestCase(TestCase):
    @vcr.use_cassette('fixtures/vcr/conversion_api-test_successful_login.yml')
    def test_successful_login(self):
        api_client = ConversionApiClient()

        self.assertIsNone(api_client.token)

        api_client._login()

        self.assertIsNotNone(api_client.token)

    @vcr.use_cassette('fixtures/vcr/conversion_api-test_failed_login.yml')
    def test_failed_login(self):
        api_client = ConversionApiClient()
        api_client.password = 'invalid'

        self.assertEqual(api_client.password, '<PASSWORD>')
        self.assertIsNone(api_client.token)

        expected_msg = \
            "400 Client Error: BAD REQUEST for url: http://localhost:8901/api/token-auth/"
        with self.assertRaisesRegex(HTTPError, "^{}$".format(re.escape(expected_msg))) as cm:
            api_client._login()

        self.assertEqual(
            API_client.reasons_for(cm.exception),
            {'non_field_errors': ['Unable to login with provided credentials.']}
        )
        self.assertIsNone(api_client.token)


class ConversionApiClientTestCase(TestCase):
    def setUp(self):
        self.request = Mock()
        self.request.build_absolute_uri.return_value = 'http://the-host.example.com/job_progress/tracker/1/'
        self.user = User.objects.create_user('user', '<EMAIL>', 'pw')
        self.bounding_box = BBoxBoundingGeometry.create_from_bounding_box_coordinates(
            40.77739734768811, 29.528980851173397, 40.77546776498174, 29.525547623634335
        )
        self.excerpt = Excerpt.objects.create(
            name='Neverland', is_active=True, is_public=True, owner=self.user, bounding_geometry=self.bounding_box
        )
        self.extraction_order = ExtractionOrder.objects.create(excerpt=self.excerpt, orderer=self.user)
        self.extraction_order.extraction_configuration = {
            'gis_formats': ['fgdb', 'spatialite'],
            'gis_options': {
                'coordinate_reference_system': 'WGS_84',
                'detail_level': 1
            }
        }
        self.api_client = ConversionApiClient()

    #
    # Unit tests:

    @mock.patch.object(ConversionApiClient, 'create_job', side_effect=[sentinel.job_1, sentinel.job_2])
    @mock.patch.object(
        ConversionApiClient, 'create_parametrization',
        create=True,  # TODO: remove 'create' once implemented
        side_effect=[sentinel.parametrization_1, sentinel.parametrization_2],
    )
    @mock.patch.object(ConversionApiClient, 'create_boundary')
    def test_extraction_order_forward_to_conversion_service(
            self, create_boundary_mock, create_parametrization_mock, create_job_mock):
        result = self.extraction_order.forward_to_conversion_service(incoming_request=self.request)

        create_boundary_mock.assert_called_once_with(self.bounding_box.geometry, name=self.excerpt.name)
        gis_conversion_options = self.extraction_order.extraction_configuration['gis_options']
        assert_that(
            create_parametrization_mock.mock_calls, contains_inanyorder(
                mock.call(create_boundary_mock.return_value, 'fgdb', gis_conversion_options),
                mock.call(create_boundary_mock.return_value, 'spatialite', gis_conversion_options),
            )
        )
        assert_that(
            create_job_mock.mock_calls, contains_inanyorder(
                mock.call(sentinel.parametrization_1, self.request),
                mock.call(sentinel.parametrization_2, self.request),
            )
        )
        assert_that(
            result, contains_inanyorder(
                sentinel.job_1,
                sentinel.job_2,
            )
        )

    #
    # Integration tests:

{'fraction_non_alphanumeric': 0.0895123580494322, 'fraction_numerical': 0.019260743709641506, 'mean_word_length': 3.2919254658385095, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6265157', 'n_tokens_mistral': 2880, 'n_tokens_neox': 2666, 'n_words': 415}