<commit_before>from nose.tools import *  # flake8: noqa

from website.project.model import ensure_schemas
from website.models import MetaSchema
from website.project.metadata.schemas import LATEST_SCHEMA_VERSION
from website.project.metadata.utils import create_jsonschema_from_metaschema
from modularodm import Q
from website.util import permissions
from website.settings import PREREG_ADMIN_TAG

from api.base.settings.defaults import API_BASE

from tests.base import ApiTestCase
from tests.factories import (
    ProjectFactory,
    RegistrationFactory,
    AuthUserFactory,
    CollectionFactory,
    DraftRegistrationFactory
)

class DraftRegistrationTestCase(ApiTestCase):

    def setUp(self):
        super(DraftRegistrationTestCase, self).setUp()
        self.user = AuthUserFactory()
        self.read_only_user = AuthUserFactory()
        self.read_write_user = AuthUserFactory()
        self.non_contributor = AuthUserFactory()

        self.public_project = ProjectFactory(is_public=True, creator=self.user)
        self.public_project.add_contributor(self.read_only_user, permissions=[permissions.READ])
        self.public_project.add_contributor(self.read_write_user, permissions=[permissions.WRITE])
        self.public_project.save()

    def prereg_metadata(self, draft):
        test_metadata = {}
        json_schema = create_jsonschema_from_metaschema(draft.registration_schema.schema)

        for key, value in json_schema['properties'].iteritems():
            response = 'Test response'
            if value['properties']['value'].get('enum'):
                response = value['properties']['value']['enum'][0]

            if value['properties']['value'].get('properties'):
                response = {'question': {'value': 'Test Response'}}

            test_metadata[key] = {'value': response}
        return test_metadata


class TestDraftRegistrationList(DraftRegistrationTestCase):

    def setUp(self):
        super(TestDraftRegistrationList, self).setUp()
        ensure_schemas()
        self.schema = MetaSchema.find_one(
            Q('name', 'eq', 'Open-Ended Registration') &
            Q('schema_version', 'eq', LATEST_SCHEMA_VERSION)
        )

        self.draft_registration = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            branched_from=self.public_project
        )

        self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id)

    def test_admin_can_view_draft_list(self):
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 1)
        assert_equal(data[0]['attributes']['registration_supplement'], self.schema._id)
        assert_equal(data[0]['id'], self.draft_registration._id)
        assert_equal(data[0]['attributes']['registration_metadata'], {})

    def test_read_only_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.read_only_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_read_write_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.read_write_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_logged_in_non_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.non_contributor.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_unauthenticated_user_cannot_view_draft_list(self):
        res = self.app.get(self.url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_draft_with_registered_node_does_not_show_up_in_draft_list(self):
        reg = RegistrationFactory(project = self.public_project)
        self.draft_registration.registered_node = reg
        self.draft_registration.save()
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 0)

    def test_draft_with_deleted_registered_node_shows_up_in_draft_list(self):
        reg = RegistrationFactory(project=self.public_project)
        self.draft_registration.registered_node = reg
        self.draft_registration.save()
        reg.is_deleted = True
        reg.save()
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 1)
        assert_equal(data[0]['attributes']['registration_supplement'], self.schema._id)
        assert_equal(data[0]['id'], self.draft_registration._id)
        assert_equal(data[0]['attributes']['registration_metadata'], {})


class TestDraftRegistrationCreate(DraftRegistrationTestCase):
    def setUp(self):
        super(TestDraftRegistrationCreate, self).setUp()
        self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id)
        ensure_schemas()
        self.open_ended_metaschema = MetaSchema.find_one(
            Q('name', 'eq', 'Open-Ended Registration') &
            Q('schema_version', 'eq', LATEST_SCHEMA_VERSION)
        )

        self.payload = {
            "data": {
                "type": "draft_registrations",
                "attributes": {
                    "registration_supplement": self.open_ended_metaschema._id
                }
            }
        }

    def test_type_is_draft_registrations(self):
        draft_data = {
            "data": {
                "type": "nodes",
                "attributes": {
                    "registration_supplement": self.open_ended_metaschema._id
                }
            }
        }
        res = self.app.post_json_api(self.url, draft_data, auth=self.user.auth, expect_errors=True)
        errors = res.json['errors'][0]
        assert_equal(errors['detail'], "Resource identifier does not match server endpoint.")
        assert_equal(res.status_code, 409)

    def test_admin_can_create_draft(self):
        url = '/{}nodes/{}/draft_registrations/?embed=branched_from&embed=initiator'.format(API_BASE, self.public_project._id)
        res = self.app.post_json_api(url, self.payload, auth=self.user.auth)
        assert_equal(res.status_code, 201)
        data = res.json['data']
        assert_equal(data['attributes']['registration_supplement'], self.open_ended_metaschema._id)
        assert_equal(data['attributes']['registration_metadata'], {})
        assert_equal(data['embeds']['branched_from']['data']['id'], self.public_project._id)
        assert_equal(data['embeds']['initiator']['data']['id'], self.user._id)

    def test_write_only_contributor_cannot_create_draft(self):
        assert_in(self.read_write_user._id, self.public_project.contributors)
        res = self.app.post_json_api(self.url, self.payload, auth=self.read_write_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_read_only_contributor_cannot_create_draft(self):<commit_msg>Remove assertion of error message in test.  It is sufficient to check status code.<commit_after>from nose.tools import *  # flake8: noqa

from website.project.model import ensure_schemas
from website.models import MetaSchema
from website.project.metadata.schemas import LATEST_SCHEMA_VERSION
from website.project.metadata.utils import create_jsonschema_from_metaschema
from modularodm import Q
from website.util import permissions
from website.settings import PREREG_ADMIN_TAG

from api.base.settings.defaults import API_BASE

from tests.base import ApiTestCase
from tests.factories import (
    ProjectFactory,
    RegistrationFactory,
    AuthUserFactory,
    CollectionFactory,
    DraftRegistrationFactory
)

class DraftRegistrationTestCase(ApiTestCase):

    def setUp(self):
        super(DraftRegistrationTestCase, self).setUp()
        self.user = AuthUserFactory()
        self.read_only_user = AuthUserFactory()
        self.read_write_user = AuthUserFactory()
        self.non_contributor = AuthUserFactory()

        self.public_project = ProjectFactory(is_public=True, creator=self.user)
        self.public_project.add_contributor(self.read_only_user, permissions=[permissions.READ])
        self.public_project.add_contributor(self.read_write_user, permissions=[permissions.WRITE])
        self.public_project.save()

    def prereg_metadata(self, draft):
        test_metadata = {}
        json_schema = create_jsonschema_from_metaschema(draft.registration_schema.schema)

        for key, value in json_schema['properties'].iteritems():
            response = 'Test response'
            if value['properties']['value'].get('enum'):
                response = value['properties']['value']['enum'][0]

            if value['properties']['value'].get('properties'):
                response = {'question': {'value': 'Test Response'}}

            test_metadata[key] = {'value': response}
        return test_metadata


class TestDraftRegistrationList(DraftRegistrationTestCase):

    def setUp(self):
        super(TestDraftRegistrationList, self).setUp()
        ensure_schemas()
        self.schema = MetaSchema.find_one(
            Q('name', 'eq', 'Open-Ended Registration') &
            Q('schema_version', 'eq', LATEST_SCHEMA_VERSION)
        )

        self.draft_registration = DraftRegistrationFactory(
            initiator=self.user,
            registration_schema=self.schema,
            branched_from=self.public_project
        )

        self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id)

    def test_admin_can_view_draft_list(self):
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 1)
        assert_equal(data[0]['attributes']['registration_supplement'], self.schema._id)
        assert_equal(data[0]['id'], self.draft_registration._id)
        assert_equal(data[0]['attributes']['registration_metadata'], {})

    def test_read_only_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.read_only_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_read_write_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.read_write_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_logged_in_non_contributor_cannot_view_draft_list(self):
        res = self.app.get(self.url, auth=self.non_contributor.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_unauthenticated_user_cannot_view_draft_list(self):
        res = self.app.get(self.url, expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_draft_with_registered_node_does_not_show_up_in_draft_list(self):
        reg = RegistrationFactory(project = self.public_project)
        self.draft_registration.registered_node = reg
        self.draft_registration.save()
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 0)

    def test_draft_with_deleted_registered_node_shows_up_in_draft_list(self):
        reg = RegistrationFactory(project=self.public_project)
        self.draft_registration.registered_node = reg
        self.draft_registration.save()
        reg.is_deleted = True
        reg.save()
        res = self.app.get(self.url, auth=self.user.auth)
        assert_equal(res.status_code, 200)
        data = res.json['data']
        assert_equal(len(data), 1)
        assert_equal(data[0]['attributes']['registration_supplement'], self.schema._id)
        assert_equal(data[0]['id'], self.draft_registration._id)
        assert_equal(data[0]['attributes']['registration_metadata'], {})


class TestDraftRegistrationCreate(DraftRegistrationTestCase):
    def setUp(self):
        super(TestDraftRegistrationCreate, self).setUp()
        self.url = '/{}nodes/{}/draft_registrations/'.format(API_BASE, self.public_project._id)
        ensure_schemas()
        self.open_ended_metaschema = MetaSchema.find_one(
            Q('name', 'eq', 'Open-Ended Registration') &
            Q('schema_version', 'eq', LATEST_SCHEMA_VERSION)
        )

        self.payload = {
            "data": {
                "type": "draft_registrations",
                "attributes": {
                    "registration_supplement": self.open_ended_metaschema._id
                }
            }
        }

    def test_type_is_draft_registrations(self):
        draft_data = {
            "data": {
                "type": "nodes",
                "attributes": {
                    "registration_supplement": self.open_ended_metaschema._id
                }
            }
        }
        res = self.app.post_json_api(self.url, draft_data, auth=self.user.auth, expect_errors=True)
        assert_equal(res.status_code, 409)

    def test_admin_can_create_draft(self):
        url = '/{}nodes/{}/draft_registrations/?embed=branched_from&embed=initiator'.format(API_BASE, self.public_project._id)
        res = self.app.post_json_api(url, self.payload, auth=self.user.auth)
        assert_equal(res.status_code, 201)
        data = res.json['data']
        assert_equal(data['attributes']['registration_supplement'], self.open_ended_metaschema._id)
        assert_equal(data['attributes']['registration_metadata'], {})
        assert_equal(data['embeds']['branched_from']['data']['id'], self.public_project._id)
        assert_equal(data['embeds']['initiator']['data']['id'], self.user._id)

    def test_write_only_contributor_cannot_create_draft(self):
        assert_in(self.read_write_user._id, self.public_project.contributors)
        res = self.app.post_json_api(self.url, self.payload, auth=self.read_write_user.auth, expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_read_only_contributor_cannot_create_draft(self):
{'fraction_non_alphanumeric': 0.11294687366472013, 'fraction_numerical': 0.005910838911835921, 'mean_word_length': 3.355769230769231, 'pattern_counts': {'":': 16, '<': 3, '<?xml version=': 0, '>': 3, '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': '2366670', 'n_tokens_mistral': 4326, 'n_tokens_neox': 4119, 'n_words': 598}