<commit_before># -*- coding: utf-8 -*-

import nose
from nose.tools import *  # noqa
import mock

import httplib as http
from tests.factories import AuthUserFactory

from dataverse.exceptions import UnauthorizedError

from framework.auth.decorators import Auth

from website.util import api_url_for
from website.addons.dataverse.tests.utils import (
    create_mock_connection, DataverseAddonTestCase, create_external_account,
)


class TestDataverseViewsAuth(DataverseAddonTestCase):

    def test_deauthorize(self):
        url = api_url_for('deauthorize_dataverse',
                          pid=self.project._primary_key)
        self.app.delete(url, auth=self.user.auth)

        self.node_settings.reload()
        assert_false(self.node_settings.dataverse_alias)
        assert_false(self.node_settings.dataverse)
        assert_false(self.node_settings.dataset_doi)
        assert_false(self.node_settings.dataset)
        assert_false(self.node_settings.user_settings)

        # Log states that node was deauthorized
        self.project.reload()
        last_log = self.project.logs[-1]
        assert_equal(last_log.action, 'dataverse_node_deauthorized')
        log_params = last_log.params
        assert_equal(log_params['node'], self.project._primary_key)
        assert_equal(log_params['project'], None)

    def test_user_config_get(self):
        url = api_url_for('dataverse_user_config_get')
        res = self.app.get(url, auth=self.user.auth)

        result = res.json.get('result')
        assert_false(result['userHasAuth'])
        assert_in('hosts', result)
        assert_in('create', result['urls'])

        # userHasAuth is true with external accounts
        self.user.external_accounts.append(create_external_account())
        self.user.save()
        res = self.app.get(url, auth=self.user.auth)

        result = res.json.get('result')
        assert_true(result['userHasAuth'])


class TestDataverseViewsConfig(DataverseAddonTestCase):

    @mock.patch('website.addons.dataverse.views.config.client.connect_from_settings')
    def test_dataverse_get_datasets(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        url = api_url_for('dataverse_get_datasets', pid=self.project._primary_key)
        params = {'alias': 'ALIAS1'}
        res = self.app.post_json(url, params, auth=self.user.auth)

        assert_equal(len(res.json['datasets']), 3)
        first = res.json['datasets'][0]
        assert_equal(first['title'], 'Example (DVN/00001)')
        assert_equal(first['doi'], 'doi:12.3456/DVN/00001')

    @mock.patch('website.addons.dataverse.views.config.client._connect')
    def test_set_user_config(self, mock_connection):

        mock_connection.return_value = create_mock_connection()

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'api_token': '<PASSWORD>'}

        # Post dataverse credentials
        self.app.post_json(url, params, auth=user.auth)
        user_settings.reload()

        # User settings have updated correctly
        assert_equal(user_settings.api_token, '<PASSWORD>')

    @mock.patch('website.addons.dataverse.views.config.client._connect')
    def test_set_user_config_fail(self, mock_connection):

        mock_connection.side_effect = UnauthorizedError('Bad credentials!')

        # Create a user with no settings
        user = AuthUserFactory()
        user.add_addon('dataverse')
        user_settings = user.get_addon('dataverse')

        url = api_url_for('dataverse_set_user_config')
        params = {'api_token': 'wrong-info'}

        # Post incorrect credentials to existing user
        res = self.app.post_json(url, params, auth=self.user.auth,
                                 expect_errors=True)
        self.user_settings.reload()

        # Original user's info has not changed
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(self.user_settings.api_token, '<PASSWORD>')

        # Post incorrect credentials to new user
        res = self.app.post_json(url, params, auth=user.auth,
                                 expect_errors=True)
        user_settings.reload()

        # New user's incorrect credentials were not saved
        assert_equal(res.status_code, http.UNAUTHORIZED)
        assert_equal(user_settings.api_token, None)

    @mock.patch('website.addons.dataverse.views.config.client.connect_from_settings')
    def test_set_dataverse_and_dataset(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        url = api_url_for('set_dataverse_and_dataset',
                          pid=self.project._primary_key)
        params = {
            'dataverse': {'alias': 'ALIAS3'},
            'dataset': {'doi': 'doi:12.3456/DVN/00003'},
        }

        # Select a different dataset
        self.app.post_json(url, params, auth=self.user.auth)
        self.project.reload()
        self.node_settings.reload()

        # New dataset was selected
        assert_equal(self.node_settings.dataverse_alias, 'ALIAS3')
        assert_equal(self.node_settings.dataset, 'Example (DVN/00003)')
        assert_equal(self.node_settings.dataset_doi, 'doi:12.3456/DVN/00003')
        assert_equal(self.node_settings.dataset_id, '18')
<commit_msg>Fix remaining Dataverse views tests<commit_after># -*- coding: utf-8 -*-

import nose
from nose.tools import *  # noqa
import mock

import httplib as http
from tests.factories import AuthUserFactory

from dataverse.exceptions import UnauthorizedError

from framework.auth.decorators import Auth

from website.util import api_url_for
from website.addons.dataverse.serializer import DataverseSerializer
from website.addons.dataverse.tests.utils import (
    create_mock_connection, DataverseAddonTestCase, create_external_account,
)


class TestDataverseViewsAuth(DataverseAddonTestCase):

    def test_deauthorize(self):
        url = api_url_for('deauthorize_dataverse',
                          pid=self.project._primary_key)
        self.app.delete(url, auth=self.user.auth)

        self.node_settings.reload()
        assert_false(self.node_settings.dataverse_alias)
        assert_false(self.node_settings.dataverse)
        assert_false(self.node_settings.dataset_doi)
        assert_false(self.node_settings.dataset)
        assert_false(self.node_settings.user_settings)

        # Log states that node was deauthorized
        self.project.reload()
        last_log = self.project.logs[-1]
        assert_equal(last_log.action, 'dataverse_node_deauthorized')
        log_params = last_log.params
        assert_equal(log_params['node'], self.project._primary_key)
        assert_equal(log_params['project'], None)

    def test_user_config_get(self):
        url = api_url_for('dataverse_user_config_get')
        res = self.app.get(url, auth=self.user.auth)

        result = res.json.get('result')
        assert_false(result['userHasAuth'])
        assert_in('hosts', result)
        assert_in('create', result['urls'])

        # userHasAuth is true with external accounts
        self.user.external_accounts.append(create_external_account())
        self.user.save()
        res = self.app.get(url, auth=self.user.auth)

        result = res.json.get('result')
        assert_true(result['userHasAuth'])


class TestDataverseViewsConfig(DataverseAddonTestCase):

    @mock.patch('website.addons.dataverse.views.config.client.connect_from_settings')
    def test_dataverse_get_datasets(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        url = api_url_for('dataverse_get_datasets', pid=self.project._primary_key)
        params = {'alias': 'ALIAS1'}
        res = self.app.post_json(url, params, auth=self.user.auth)

        assert_equal(len(res.json['datasets']), 3)
        first = res.json['datasets'][0]
        assert_equal(first['title'], 'Example (DVN/00001)')
        assert_equal(first['doi'], 'doi:12.3456/DVN/00001')

    def test_dataverse_get_user_accounts(self):
        external_account = create_external_account()
        self.user.external_accounts.append(external_account)
        self.user.external_accounts.append(create_external_account())
        self.user.save()

        url = api_url_for('dataverse_get_user_accounts')
        res = self.app.get(url, auth=self.user.auth)
        accounts = res.json['accounts']

        assert_equal(len(accounts), 2)
        serializer = DataverseSerializer(user_settings=self.user_settings)
        assert_equal(
            accounts[0], serializer.serialize_account(external_account),
        )

    def test_dataverse_get_user_accounts_no_accounts(self):
        url = api_url_for('dataverse_get_user_accounts')
        res = self.app.get(url, auth=self.user.auth)
        accounts = res.json['accounts']

        assert_equal(len(accounts), 0)

    @mock.patch('website.addons.dataverse.views.config.client._connect')
    def test_dataverse_add_external_account(self, mock_connection):
        mock_connection.return_value = create_mock_connection()
        host = 'myfakehost.data.verse'
        token = '<PASSWORD>'

        url = api_url_for('dataverse_add_external_account')
        params = {'host': host, 'api_token': <PASSWORD>}
        self.app.post_json(url, params, auth=self.user.auth)
        self.user.reload()

        assert_equal(len(self.user.external_accounts), 1)
        external_account = self.user.external_accounts[0]
        assert_equal(external_account.provider, 'dataverse')
        assert_equal(external_account.oauth_key, host)
        assert_equal(external_account.oauth_secret, token)

    @mock.patch('website.addons.dataverse.views.config.client._connect')
    def test_dataverse_add_external_account_fail(self, mock_connection):
        mock_connection.side_effect = UnauthorizedError('Bad credentials!')
        host = 'myfakehost.data.verse'
        token = '<PASSWORD>'

        url = api_url_for('dataverse_add_external_account')
        params = {'host': host, 'api_token': token}
        res = self.app.post_json(
            url, params, auth=self.user.auth, expect_errors=True,
        )
        self.user.reload()

        assert_equal(len(self.user.external_accounts), 0)
        assert_equal(res.status_code, http.UNAUTHORIZED)

    @mock.patch('website.addons.dataverse.views.config.client.connect_from_settings')
    def test_set_dataverse_and_dataset(self, mock_connection):
        mock_connection.return_value = create_mock_connection()

        url = api_url_for('set_dataverse_and_dataset',
                          pid=self.project._primary_key)
        params = {
            'dataverse': {'alias': 'ALIAS3'},
            'dataset': {'doi': 'doi:12.3456/DVN/00003'},
        }

        # Select a different dataset
        self.app.post_json(url, params, auth=self.user.auth)
        self.project.reload()
        self.node_settings.reload()

        # New dataset was selected
        assert_equal(self.node_settings.dataverse_alias, 'ALIAS3')
        assert_equal(self.node_settings.dataset, 'Example (DVN/00003)')
        assert_equal(self.node_settings.dataset_doi, 'doi:12.3456/DVN/00003')
        assert_equal(self.node_settings.dataset_id, '18')

{'fraction_non_alphanumeric': 0.10772071755188181, 'fraction_numerical': 0.009672880759760817, 'mean_word_length': 3.2389116660454715, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3391154', 'n_tokens_mistral': 3551, 'n_tokens_neox': 3408, 'n_words': 528}