<commit_before>from __future__ import absolute_import

import os
import json
from datetime import datetime

from nose.tools import assert_equal, assert_in

from app import create_app, db
from app.models import Service, Supplier, ContactInformation, Framework

TEST_SUPPLIERS_COUNT = 3


class WSGIApplicationWithEnvironment(object):
    def __init__(self, app, **kwargs):
        self.app = app
        self.kwargs = kwargs

    def __call__(self, environ, start_response):
        for key, value in self.kwargs.items():
            environ[key] = value
        return self.app(environ, start_response)


class BaseApplicationTest(object):
    lots = {
        "iaas": "G6-IaaS.json",
        "saas": "G6-SaaS.json",
        "paas": "G6-PaaS.json",
        "scs": "G6-SCS.json"
    }

    config = None

    def setup(self):
        self.app = create_app('test')
        self.client = self.app.test_client()
        self.setup_authorization()
        self.setup_frameworks()

    def setup_authorization(self):
        """Set up bearer token and pass on all requests"""
        valid_token = 'valid-token'
        self.app.wsgi_app = WSGIApplicationWithEnvironment(
            self.app.wsgi_app,
            HTTP_AUTHORIZATION='Bearer {}'.format(valid_token))
        self._auth_tokens = os.environ.get('DM_API_AUTH_TOKENS')
        os.environ['DM_API_AUTH_TOKENS'] = valid_token

    def do_not_provide_access_token(self):
        self.app.wsgi_app = self.app.wsgi_app.app

    def setup_frameworks(self):
        with self.app.app_context():
            if Framework.query.count() == 0:
                db.session.add(
                    Framework(id=1, name="G-Cloud 6", expired=False))
                db.session.add(
                    Framework(id=2, name="G-Cloud 4", expired=True))
                db.session.add(
                    Framework(id=3, name="G-Cloud 5", expired=False))
                db.session.commit()

    def setup_dummy_suppliers(self, n):
        with self.app.app_context():
            for i in range(n):
                db.session.add(
                    Supplier(
                        supplier_id=i,
                        name=u"Supplier {}".format(i),
                        description="",
                        clients=[]
                    )
                )
                db.session.add(
                    ContactInformation(
                        supplier_id=i,
                        contact_name=u"Contact for Supplier {}".format(i),
                        email=u"{}<EMAIL>".format(i),
                        postcode=u"SW1A 1AA"
                    )
                )
            db.session.commit()

    def setup_dummy_services_including_unpublished(self, n):
        now = datetime.now()
        with self.app.app_context():
            self.setup_dummy_suppliers(TEST_SUPPLIERS_COUNT)
            for i in range(n):
                db.session.add(Service(service_id=i,
                                       supplier_id=i % TEST_SUPPLIERS_COUNT,
                                       updated_at=now,
                                       status='published',
                                       created_at=now,
                                       updated_by='tests',
                                       updated_reason='test data',
                                       data={'foo': 'bar'},
                                       framework_id=1))
            # Add extra 'enabled' and 'disabled' services
            db.session.add(Service(service_id=n + 1,
                                   supplier_id=n % TEST_SUPPLIERS_COUNT,
                                   updated_at=now,
                                   status='disabled',
                                   created_at=now,
                                   updated_by='tests',
                                   updated_reason='test data',
                                   data={'foo': 'bar'},
                                   framework_id=1))
            db.session.add(Service(service_id=n + 2,
                                   supplier_id=n % TEST_SUPPLIERS_COUNT,
                                   updated_at=now,
                                   status='enabled',
                                   created_at=now,
                                   updated_by='tests',
                                   updated_reason='test data',
                                   data={'foo': 'bar'},
                                   framework_id=1))
            # Add an extra supplier that will have no services
            db.session.add(
                Supplier(supplier_id=TEST_SUPPLIERS_COUNT, name=u"Supplier {}"
                         .format(TEST_SUPPLIERS_COUNT))
            )
            db.session.add(
                ContactInformation(
                    supplier_id=TEST_SUPPLIERS_COUNT,
                    contact_name=u"Contact for Supplier {}".format(i),
                    email=u"{}<EMAIL>".format(i),
                    postcode=u"SW1A 1AA"
                )
            )
            db.session.commit()

    def teardown(self):
        self.teardown_authorization()
        self.teardown_database()

    def teardown_authorization(self):
        if self._auth_tokens is None:
            del os.environ['DM_API_AUTH_TOKENS']
        else:
            os.environ['DM_API_AUTH_TOKENS'] = self._auth_tokens

    def teardown_database(self):
        with self.app.app_context():
            db.session.remove()
            for table in reversed(db.metadata.sorted_tables):
                db.engine.execute(table.delete())
            db.get_engine(self.app).dispose()

    def load_example_listing(self, name):
        file_path = os.path.join("example_listings", "{}.json".format(name))
        with open(file_path) as f:
            return json.load(f)

    def first_by_rel(self, rel, links):
        for link in links:
            if link['rel'] == rel:
                return link


class JSONUpdateTestMixin(object):
    """
    Tests to verify that endpoints that accept JSON.
    """
    endpoint = None
    method = None
    client = None

    def test_non_json_causes_failure(self):
        response = self.client.open(
            self.endpoint,<commit_msg>Do not empty the Framework table<commit_after>from __future__ import absolute_import

import os
import json
from datetime import datetime

from nose.tools import assert_equal, assert_in

from app import create_app, db
from app.models import Service, Supplier, ContactInformation, Framework

TEST_SUPPLIERS_COUNT = 3


class WSGIApplicationWithEnvironment(object):
    def __init__(self, app, **kwargs):
        self.app = app
        self.kwargs = kwargs

    def __call__(self, environ, start_response):
        for key, value in self.kwargs.items():
            environ[key] = value
        return self.app(environ, start_response)


class BaseApplicationTest(object):
    lots = {
        "iaas": "G6-IaaS.json",
        "saas": "G6-SaaS.json",
        "paas": "G6-PaaS.json",
        "scs": "G6-SCS.json"
    }

    config = None

    def setup(self):
        self.app = create_app('test')
        self.client = self.app.test_client()
        self.setup_authorization()

    def setup_authorization(self):
        """Set up bearer token and pass on all requests"""
        valid_token = '<PASSWORD>'
        self.app.wsgi_app = WSGIApplicationWithEnvironment(
            self.app.wsgi_app,
            HTTP_AUTHORIZATION='Bearer {}'.format(valid_token))
        self._auth_tokens = os.environ.get('DM_API_AUTH_TOKENS')
        os.environ['DM_API_AUTH_TOKENS'] = valid_token

    def do_not_provide_access_token(self):
        self.app.wsgi_app = self.app.wsgi_app.app

    def setup_dummy_suppliers(self, n):
        with self.app.app_context():
            for i in range(n):
                db.session.add(
                    Supplier(
                        supplier_id=i,
                        name=u"Supplier {}".format(i),
                        description="",
                        clients=[]
                    )
                )
                db.session.add(
                    ContactInformation(
                        supplier_id=i,
                        contact_name=u"Contact for Supplier {}".format(i),
                        email=u"{}<EMAIL>".<EMAIL>(i),
                        postcode=u"SW1A 1AA"
                    )
                )
            db.session.commit()

    def setup_dummy_services_including_unpublished(self, n):
        now = datetime.now()
        with self.app.app_context():
            self.setup_dummy_suppliers(TEST_SUPPLIERS_COUNT)
            for i in range(n):
                db.session.add(Service(service_id=i,
                                       supplier_id=i % TEST_SUPPLIERS_COUNT,
                                       updated_at=now,
                                       status='published',
                                       created_at=now,
                                       updated_by='tests',
                                       updated_reason='test data',
                                       data={'foo': 'bar'},
                                       framework_id=1))
            # Add extra 'enabled' and 'disabled' services
            db.session.add(Service(service_id=n + 1,
                                   supplier_id=n % TEST_SUPPLIERS_COUNT,
                                   updated_at=now,
                                   status='disabled',
                                   created_at=now,
                                   updated_by='tests',
                                   updated_reason='test data',
                                   data={'foo': 'bar'},
                                   framework_id=1))
            db.session.add(Service(service_id=n + 2,
                                   supplier_id=n % TEST_SUPPLIERS_COUNT,
                                   updated_at=now,
                                   status='enabled',
                                   created_at=now,
                                   updated_by='tests',
                                   updated_reason='test data',
                                   data={'foo': 'bar'},
                                   framework_id=1))
            # Add an extra supplier that will have no services
            db.session.add(
                Supplier(supplier_id=TEST_SUPPLIERS_COUNT, name=u"Supplier {}"
                         .format(TEST_SUPPLIERS_COUNT))
            )
            db.session.add(
                ContactInformation(
                    supplier_id=TEST_SUPPLIERS_COUNT,
                    contact_name=u"Contact for Supplier {}".format(i),
                    email=u"{}<EMAIL>".format(i),
                    postcode=u"SW1A 1AA"
                )
            )
            db.session.commit()

    def teardown(self):
        self.teardown_authorization()
        self.teardown_database()

    def teardown_authorization(self):
        if self._auth_tokens is None:
            del os.environ['DM_API_AUTH_TOKENS']
        else:
            os.environ['DM_API_AUTH_TOKENS'] = self._auth_tokens

    def teardown_database(self):
        with self.app.app_context():
            db.session.remove()
            for table in reversed(db.metadata.sorted_tables):
                if table.name != "frameworks":
                    db.engine.execute(table.delete())
            Framework.query.filter(Framework.id >= 100).delete()
            db.session.commit()
            db.get_engine(self.app).dispose()

    def load_example_listing(self, name):
        file_path = os.path.join("example_listings", "{}.json".format(name))
        with open(file_path) as f:
            return json.load(f)

    def first_by_rel(self, rel, links):
        for link in links:
            if link['rel'] == rel:
                return link


class JSONUpdateTestMixin(object):
    """
    Tests to verify that endpoints that accept JSON.
    """
    endpoint = None
    method = None
    client = None

    def test_non_json_causes_failure(self):
        response = self.client.open(
            self.endpoint,
{'fraction_non_alphanumeric': 0.0942094455852156, 'fraction_numerical': 0.0031211498973305954, 'mean_word_length': 1.3578621223857474, 'pattern_counts': {'":': 9, '<': 9, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 48, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5355629', 'n_tokens_mistral': 3336, 'n_tokens_neox': 3200, 'n_words': 594}