<commit_before>"""
    I fantasize and idealize myself as Bugs Bunny, but I know deep down I'm
    <NAME>.
                    - <NAME>

"""
import json
import random

from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from rest_framework import status
from rest_framework.authtoken.models import Token

from dpn.data.models import Node, RegistryEntry, Transfer, UserProfile
from dpn.data.utils import dpn_strptime
from dpn.data.tests.utils import make_test_transfers, make_test_registry_entries
from dpn.data.tests.utils import make_test_nodes, make_registry_postdata
from dpn.data.tests.utils import make_test_user


def _make_api_user():
    "Makes a user with a token in the api_user group."
    return make_test_user("apiuser", "apiuser", "<EMAIL>", "api_users")

def _make_api_admin():
    "Makes a user with a token in the api_admin group."
    return make_test_user("adminuser", "adminuser", "<EMAIL>",
                          "api_admins", superuser=True)

def _make_auth_user():
    "Makes a user with a token but no group."
    return make_test_user("authuser", "authuser", "<EMAIL>", None)

# # List Views

class RegistryListViewTest(APITestCase):

    fixtures = ['../data/GroupPermissions.json', ]

    def setUp(self):
        # Setup Test Data
        make_test_nodes()
        make_test_registry_entries(100)
        make_test_transfers()

        self.url = reverse('api:registry-list')

        # setup Non API user
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()

    def test_get(self):
        # It should not authorize an unauthenticated user
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # It should authorize an authenticated user.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="token %s" % token.key)
        response = self.client.get(self.url)

        entries = RegistryEntry.objects.all()
        data = json.loads(response.content.decode('utf8'))

        # It should contain the right count of registry entries.
        self.assertEqual(data['count'], entries.count())
        previous = None
        for result in data['results']:
            current = dpn_strptime(result["last_modified_date"])
            if previous:
                self.assertTrue(current > previous)
            previous = current

    def test_put(self):
        # It should not allow this method.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.put(self.url, {})
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

    def test_patch(self):
        # It should not allow this method.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.patch(self.url, {})
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

    def test_post(self):
        data = make_registry_postdata()

        # It should not allows api_users to create a record
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

        # It should allow api_admins to create a record.
        token = Token.objects.get(user=self.api_admin)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data, format="json")
        self.assertEqual(rsp.status_code, status.HTTP_201_CREATED)


class NodeListViewTest(APITestCase):
    fixtures = ["../data/GroupPermissions.json", ]

    def setUp(self):
        make_test_nodes()
        self.url = reverse('api:node-list')
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()
        self.auth_user = _make_auth_user()

    def test_get(self):
        # It should deny access to anonomous users.
        rsp = self.client.get(self.url)
        self.assertEqual(rsp.status_code, status.HTTP_401_UNAUTHORIZED)

        def _test_each_group(u):  # It should list nodes for authorized users
            profile = UserProfile.objects.get(user=u)
            token = Token.objects.get(user=u)
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            rsp = self.client.get(self.url)
            data = json.loads(rsp.content.decode('utf8'))
            self.assertEqual(data['count'], 5)

        _test_each_group(self.api_user)
        _test_each_group(self.api_admin)

    def test_post(self):
        data = {
            "name": "TestNode",
            "namespace": "testnode",
            "api_root": "https://test.api.org/",
            "storage": [{"region": "NJ", "type": "Test storage"},],
            # "ssh_username": "dpntestnode",
        }
        # It should deny an unauthorized user.
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_401_UNAUTHORIZED)

        # It should deny an api_user.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

        # It should allow api_admin to create a node.
        token = Token.objects.get(user=self.api_admin)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_201_CREATED, rsp.content)

    def test_bad_requests(self):
        tokens = [Token.objects.get(user=self.api_admin),
                  Token.objects.get(user=self.api_user)]
        for token in tokens:
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            # put not allowed
            rsp = self.client.put(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)
            # patch not allowed
            rsp = self.client.patch(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)
            # delete not allowed
            rsp = self.client.delete(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)


class TransferListViewTest(APITestCase):

    fixtures = ['../data/GroupPermissions.json', ]

    def setUp(self):
        # Setup Test Data
        make_test_nodes()
        make_test_registry_entries(100)
        make_test_transfers()
        self.url = reverse('api:transfer-list')
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()

    def test_get(self):

        def _test_return_count(user, url, exp_count):
            # Tests for expected object count.
            token = Token.objects.get(user=user)
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            rsp = self.client.get(url)
            data = json.loads(rsp.content.decode('utf8'))
            self.assertEqual(data["count"], exp_count, "%r" % data)
            self.assertEqual(rsp.status_code, status.HTTP_200_OK)

        # It should return only transfers for the users node.
        xfers = Transfer.objects.filter(node=self.api_user.profile.node)
        _test_return_count(self.api_user, self.url, xfers.count())

        # It should return all transfers for superusers.
        xfers = Transfer.objects.all()
        _test_return_count(self.api_admin, self.url, xfers.count())

        mynode = Node.objects.get(me=True)
        # It should filter transfers by dpn_object_id
        reg = RegistryEntry.objects.filter(first_node=mynode).order_by('?')[0]<commit_msg>Still working on Travis bug.<commit_after>"""
    I fantasize and idealize myself as Bugs Bunny, but I know deep down I'm
    Daffy Duck.
                    - <NAME>

"""
import json
import random

from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from rest_framework import status
from rest_framework.authtoken.models import Token

from dpn.data.models import Node, RegistryEntry, Transfer, UserProfile
from dpn.data.utils import dpn_strptime
from dpn.data.tests.utils import make_test_transfers, make_test_registry_entries
from dpn.data.tests.utils import make_test_nodes, make_registry_postdata
from dpn.data.tests.utils import make_test_user


def _make_api_user():
    "Makes a user with a token in the api_user group."
    return make_test_user("apiuser", "apiuser", "<EMAIL>", "api_users")

def _make_api_admin():
    "Makes a user with a token in the api_admin group."
    return make_test_user("adminuser", "adminuser", "<EMAIL>",
                          "api_admins", superuser=True)

def _make_auth_user():
    "Makes a user with a token but no group."
    return make_test_user("authuser", "authuser", "<EMAIL>", None)

# # List Views

class RegistryListViewTest(APITestCase):

    fixtures = ['../data/GroupPermissions.json', ]

    def setUp(self):
        # Setup Test Data
        make_test_nodes()
        make_test_registry_entries(100)
        make_test_transfers()

        self.url = reverse('api:registry-list')

        # setup Non API user
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()

    def test_get(self):
        # It should not authorize an unauthenticated user
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        # It should authorize an authenticated user.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="token %s" % token.key)
        response = self.client.get(self.url)

        entries = RegistryEntry.objects.all()

        # It should contain the right count of registry entries.
        self.assertEqual(response.data['count'], entries.count())
        previous = None
        for result in response.data['results']:
            current = dpn_strptime(result["last_modified_date"])
            if previous:
                self.assertTrue(current > previous)
            previous = current

    def test_put(self):
        # It should not allow this method.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.put(self.url, {})
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

    def test_patch(self):
        # It should not allow this method.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.patch(self.url, {})
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

    def test_post(self):
        data = make_registry_postdata()

        # It should not allows api_users to create a record
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

        # It should allow api_admins to create a record.
        token = Token.objects.get(user=self.api_admin)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data, format="json")
        self.assertEqual(rsp.status_code, status.HTTP_201_CREATED)


class NodeListViewTest(APITestCase):
    fixtures = ["../data/GroupPermissions.json", ]

    def setUp(self):
        make_test_nodes()
        self.url = reverse('api:node-list')
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()
        self.auth_user = _make_auth_user()

    def test_get(self):
        # It should deny access to anonomous users.
        rsp = self.client.get(self.url)
        self.assertEqual(rsp.status_code, status.HTTP_401_UNAUTHORIZED)

        def _test_each_group(u):  # It should list nodes for authorized users
            token = Token.objects.get(user=u)
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            rsp = self.client.get(self.url)
            self.assertEqual(rsp.data['count'], 5)

        _test_each_group(self.api_user)
        _test_each_group(self.api_admin)

    def test_post(self):
        data = {
            "name": "TestNode",
            "namespace": "testnode",
            "api_root": "https://test.api.org/",
            "storage": [{"region": "NJ", "type": "Test storage"},],
            # "ssh_username": "dpntestnode",
        }
        # It should deny an unauthorized user.
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_401_UNAUTHORIZED)

        # It should deny an api_user.
        token = Token.objects.get(user=self.api_user)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_403_FORBIDDEN)

        # It should allow api_admin to create a node.
        token = Token.objects.get(user=self.api_admin)
        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        rsp = self.client.post(self.url, data)
        self.assertEqual(rsp.status_code, status.HTTP_201_CREATED, rsp.content)

    def test_bad_requests(self):
        tokens = [Token.objects.get(user=self.api_admin),
                  Token.objects.get(user=self.api_user)]
        for token in tokens:
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            # put not allowed
            rsp = self.client.put(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)
            # patch not allowed
            rsp = self.client.patch(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)
            # delete not allowed
            rsp = self.client.delete(self.url)
            self.assertEqual(rsp.status_code,
                             status.HTTP_405_METHOD_NOT_ALLOWED)


class TransferListViewTest(APITestCase):

    fixtures = ['../data/GroupPermissions.json', ]

    def setUp(self):
        # Setup Test Data
        make_test_nodes()
        make_test_registry_entries(100)
        make_test_transfers()
        self.url = reverse('api:transfer-list')
        self.api_user = _make_api_user()
        self.api_admin = _make_api_admin()

    def test_get(self):

        def _test_return_count(user, url, exp_count):
            # Tests for expected object count.
            token = Token.objects.get(user=user)
            self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
            rsp = self.client.get(url)
            self.assertEqual(rsp.data['count'], exp_count)
            self.assertEqual(rsp.status_code, status.HTTP_200_OK)

        # It should return only transfers for the users node.
        xfers = Transfer.objects.filter(node=self.api_user.profile.node)
        _test_return_count(self.api_user, self.url, xfers.count())

        # It should return all transfers for superusers.
        xfers = Transfer.objects.all()
        _test_return_count(self.api_admin, self.url, xfers.count())

        mynode = Node.objects.get(me=True)
        # It should filter transfers by dpn_object_id
        reg = RegistryEntry.objects.filter(first_node=mynode).order_by('?')[0]
{'fraction_non_alphanumeric': 0.10534226842863406, 'fraction_numerical': 0.006075029748857017, 'mean_word_length': 2.6531686113017616, 'pattern_counts': {'":': 14, '<': 12, '<?xml version=': 0, '>': 14, 'https://': 2, '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': '2536066', 'n_tokens_mistral': 5007, 'n_tokens_neox': 4870, 'n_words': 992}