<commit_before># -*- coding: utf-8 -*-
import httplib as http
import importlib
import pkgutil

import pytest
from pytz import utc
from datetime import datetime
import urllib

from nose.tools import *  # flake8: noqa
import re

from tests.base import ApiTestCase, DbTestCase
from osf_tests import factories
from tests.utils import make_drf_request_with_version

from api.base.settings.defaults import API_BASE
from api.base.serializers import JSONAPISerializer, BaseAPISerializer
from api.base import serializers as base_serializers
from api.nodes.serializers import NodeSerializer, RelationshipField
from api.waffle.serializers import WaffleSerializer, BaseWaffleSerializer
from api.registrations.serializers import RegistrationSerializer

SER_MODULES = []
for loader, name, _ in pkgutil.iter_modules(['api']):
    if name != 'base' and name != 'test':
        try:
            SER_MODULES.append(
                importlib.import_module(
                    'api.{}.serializers'.format(name)
                )
            )
        except ImportError:
            pass

SER_CLASSES = []
for mod in SER_MODULES:
    for name, val in mod.__dict__.iteritems():
        try:
            if issubclass(val, BaseAPISerializer):
                if 'JSONAPI' in name or 'BaseAPI' in name:
                    continue
                SER_CLASSES.append(val)
        except TypeError:
            pass


class FakeModel(object):

    def null_field(self):
        return None

    def valued_field(self):
        return 'Some'

    null = None
    foo = 'bar'

    pk = '1234'


class FakeSerializer(base_serializers.JSONAPISerializer):

    class Meta:
        type_ = 'foos'

    links = base_serializers.LinksField({
        'null_field': 'null_field',
        'valued_field': 'valued_field',
    })
    null_link_field = base_serializers.RelationshipField(
        related_view='nodes:node-detail',
        related_view_kwargs={'node_id': '<null>'},
    )
    valued_link_field = base_serializers.RelationshipField(
        related_view='nodes:node-detail',
        related_view_kwargs={'node_id': '<foo>'},
    )

    def null_field(*args, **kwargs):
        return None

    def valued_field(*args, **kwargs):
        return 'http://foo.com'


class TestSerializerMetaType(ApiTestCase):
    def test_expected_serializers_have_meta_types(self):
        for ser in SER_CLASSES:
            assert hasattr(
                ser, 'Meta'
            ), 'Serializer {} has no Meta'.format(ser)
            assert hasattr(
                ser.Meta, 'type_'
            ), 'Serializer {} has no Meta.type_'.format(ser)


class TestNodeSerializerAndRegistrationSerializerDifferences(ApiTestCase):
    """
    All fields on the Node Serializer other than the few we can serialize for withdrawals must be redeclared on the
    Registration Serializer and wrapped in HideIfWithdrawal

    HideIfRegistration fields should not be serialized on registrations.
    """

    def setUp(self):
        super(TestNodeSerializerAndRegistrationSerializerDifferences, self).setUp()

        self.node = factories.ProjectFactory(is_public=True)
        self.registration = factories.RegistrationFactory(
            project=self.node, is_public=True)

        self.url = '/{}nodes/{}/'.format(API_BASE, self.node._id)
        self.reg_url = '/{}registrations/{}/'.format(
            API_BASE, self.registration._id)

    def test_registration_serializer(self):

        # fields that are visible for withdrawals
        visible_on_withdrawals = [
            'contributors',
            'implicit_contributors',
            'date_created',
            'date_modified',
            'description',
            'id',
            'links',
            'registration',
            'title',
            'type',
            'current_user_can_comment',
            'current_user_is_contributor',
            'preprint',
            'subjects']
        # fields that do not appear on registrations
        non_registration_fields = ['registrations', 'draft_registrations', 'templated_by_count', 'settings']

        for field in NodeSerializer._declared_fields:
            assert_in(field, RegistrationSerializer._declared_fields)
            reg_field = RegistrationSerializer._declared_fields[field]

            if field not in visible_on_withdrawals and field not in non_registration_fields:
                assert_true(
                    isinstance(reg_field, base_serializers.HideIfWithdrawal) or
                    isinstance(reg_field, base_serializers.ShowIfVersion) or
                    isinstance(reg_field, base_serializers.ShowIfAdminScopeOrAnonymous)
                )

    def test_hide_if_registration_fields(self):

        node_res = self.app.get(self.url)
        node_relationships = node_res.json['data']['relationships']<commit_msg>Add wiki_enabled to list of visible withdrawn registration fields<commit_after># -*- coding: utf-8 -*-
import httplib as http
import importlib
import pkgutil

import pytest
from pytz import utc
from datetime import datetime
import urllib

from nose.tools import *  # flake8: noqa
import re

from tests.base import ApiTestCase, DbTestCase
from osf_tests import factories
from tests.utils import make_drf_request_with_version

from api.base.settings.defaults import API_BASE
from api.base.serializers import JSONAPISerializer, BaseAPISerializer
from api.base import serializers as base_serializers
from api.nodes.serializers import NodeSerializer, RelationshipField
from api.waffle.serializers import WaffleSerializer, BaseWaffleSerializer
from api.registrations.serializers import RegistrationSerializer

SER_MODULES = []
for loader, name, _ in pkgutil.iter_modules(['api']):
    if name != 'base' and name != 'test':
        try:
            SER_MODULES.append(
                importlib.import_module(
                    'api.{}.serializers'.format(name)
                )
            )
        except ImportError:
            pass

SER_CLASSES = []
for mod in SER_MODULES:
    for name, val in mod.__dict__.iteritems():
        try:
            if issubclass(val, BaseAPISerializer):
                if 'JSONAPI' in name or 'BaseAPI' in name:
                    continue
                SER_CLASSES.append(val)
        except TypeError:
            pass


class FakeModel(object):

    def null_field(self):
        return None

    def valued_field(self):
        return 'Some'

    null = None
    foo = 'bar'

    pk = '1234'


class FakeSerializer(base_serializers.JSONAPISerializer):

    class Meta:
        type_ = 'foos'

    links = base_serializers.LinksField({
        'null_field': 'null_field',
        'valued_field': 'valued_field',
    })
    null_link_field = base_serializers.RelationshipField(
        related_view='nodes:node-detail',
        related_view_kwargs={'node_id': '<null>'},
    )
    valued_link_field = base_serializers.RelationshipField(
        related_view='nodes:node-detail',
        related_view_kwargs={'node_id': '<foo>'},
    )

    def null_field(*args, **kwargs):
        return None

    def valued_field(*args, **kwargs):
        return 'http://foo.com'


class TestSerializerMetaType(ApiTestCase):
    def test_expected_serializers_have_meta_types(self):
        for ser in SER_CLASSES:
            assert hasattr(
                ser, 'Meta'
            ), 'Serializer {} has no Meta'.format(ser)
            assert hasattr(
                ser.Meta, 'type_'
            ), 'Serializer {} has no Meta.type_'.format(ser)


class TestNodeSerializerAndRegistrationSerializerDifferences(ApiTestCase):
    """
    All fields on the Node Serializer other than the few we can serialize for withdrawals must be redeclared on the
    Registration Serializer and wrapped in HideIfWithdrawal

    HideIfRegistration fields should not be serialized on registrations.
    """

    def setUp(self):
        super(TestNodeSerializerAndRegistrationSerializerDifferences, self).setUp()

        self.node = factories.ProjectFactory(is_public=True)
        self.registration = factories.RegistrationFactory(
            project=self.node, is_public=True)

        self.url = '/{}nodes/{}/'.format(API_BASE, self.node._id)
        self.reg_url = '/{}registrations/{}/'.format(
            API_BASE, self.registration._id)

    def test_registration_serializer(self):

        # fields that are visible for withdrawals
        visible_on_withdrawals = [
            'contributors',
            'implicit_contributors',
            'date_created',
            'date_modified',
            'description',
            'id',
            'links',
            'registration',
            'title',
            'type',
            'current_user_can_comment',
            'current_user_is_contributor',
            'preprint',
            'subjects',
            'wiki_enabled']
        # fields that do not appear on registrations
        non_registration_fields = ['registrations', 'draft_registrations', 'templated_by_count', 'settings']

        for field in NodeSerializer._declared_fields:
            assert_in(field, RegistrationSerializer._declared_fields)
            reg_field = RegistrationSerializer._declared_fields[field]

            if field not in visible_on_withdrawals and field not in non_registration_fields:
                assert_true(
                    isinstance(reg_field, base_serializers.HideIfWithdrawal) or
                    isinstance(reg_field, base_serializers.ShowIfVersion) or
                    isinstance(reg_field, base_serializers.ShowIfAdminScopeOrAnonymous)
                )

    def test_hide_if_registration_fields(self):

        node_res = self.app.get(self.url)
        node_relationships = node_res.json['data']['relationships']
{'fraction_non_alphanumeric': 0.08520041109969168, 'fraction_numerical': 0.0012332990750256938, 'mean_word_length': 2.5854826823876196, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, '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': '5811599', 'n_tokens_mistral': 2762, 'n_tokens_neox': 2643, 'n_words': 630}