<commit_before>"""
Test controller behavior.
"""
from base64 import b64encode
from contextlib import contextmanager
from json import loads
from os import environ
from os.path import dirname, exists, join
from shutil import copyfile, rmtree
from tempfile import mkdtemp
from textwrap import dedent

from mock import patch
from mockredis import MockRedis
from nose.tools import assert_raises, eq_, ok_
from requests import codes

from cheddar.app import create_app


class TestControllers(object):

    def setup(self):
        self.config_dir = mkdtemp()
        self.config_file = join(self.config_dir, "cheddar.conf")
        self.local_cache_dir = mkdtemp()
        self.remote_cache_dir = mkdtemp()
        self.username = "username"
        self.password = "password"

        with open(self.config_file, "w") as file_:
            file_.write('LOCAL_CACHE_DIR = "{}"\n'.format(self.local_cache_dir))
            file_.write('REMOTE_CACHE_DIR = "{}"\n'.format(self.remote_cache_dir))

        self.previous_config_file = environ.get("CHEDDAR_SETTINGS")
        environ["CHEDDAR_SETTINGS"] = self.config_file

        with patch('cheddar.configure.Redis', MockRedis):
            self.app = create_app(testing=True)

        self.client = self.app.test_client()
        self.use_json = dict(accept="application/json; charset=UTF-8")
        self.use_auth = dict(authorization="Basic {}".format(b64encode("{}:{}".format(self.username,
                                                                                      self.password))))
        self.app.redis.set("cheddar.user.{}".format(self.username), self.password)

    def teardown(self):
        if self.previous_config_file is None:
            del environ["CHEDDAR_SETTINGS"]
        else:
            environ["CHEDDAR_SETTINGS"] = self.previous_config_file

        rmtree(self.local_cache_dir)
        rmtree(self.remote_cache_dir)
        rmtree(self.config_dir)

    def test_index_template_render(self):
        result = self.client.get("/")
        eq_(result.status_code, codes.ok)

    def test_index_template_json(self):
        result = self.client.get("/", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(history=[]))

    def test_get_projects_no_projects_template_render(self):
        result = self.client.get("/simple")
        eq_(result.status_code, codes.ok)

    def test_get_projects_no_project_json(self):
        result = self.client.get("/simple", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(projects=[]))

    def test_get_projects_two_projects_json(self):
        self.app.projects.add_metadata({"name": "foo", "version": "1.0"})
        self.app.projects.add_metadata({"name": "bar", "version": "1.1"})

        result = self.client.get("/simple", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(projects=["bar", "foo"]))

    def test_get_project_local_template_render(self):
        self.app.projects.add_metadata({"name": "foo", "version": "1.0", "_filename": "foo-1.0.tar.gz"})
        self.app.projects.add_metadata({"name": "foo", "version": "1.1", "_filename": "foo-1.1.tar.gz"})
        self.app.projects.add_metadata({"name": "foo", "version": "1.0.dev1", "_filename": "foo-1.0.dev1.tar.gz"})

        result = self.client.get("/simple/foo")

        eq_(result.status_code, codes.ok)
        iter_ = self.app.index.remote._iter_version_links(result.data, "http://pypi.python.org/simple")
        eq_(iter_.next(), ("foo-1.0.dev1.tar.gz", "/local/foo-1.0.dev1.tar.gz"))
        eq_(iter_.next(), ("foo-1.0.tar.gz", "/local/foo-1.0.tar.gz"))
        eq_(iter_.next(), ("foo-1.1.tar.gz", "/local/foo-1.1.tar.gz"))
        with assert_raises(StopIteration):
            iter_.next()

    def test_get_project_remote_template_render(self):
        with self._mocked_get("http://pypi.python.org/simple/foo", codes.ok) as mock_get:
            mock_get.return_value.text = dedent("""\
                <html><commit_msg>Fix sort order in test.<commit_after>"""
Test controller behavior.
"""
from base64 import b64encode
from contextlib import contextmanager
from json import loads
from os import environ
from os.path import dirname, exists, join
from shutil import copyfile, rmtree
from tempfile import mkdtemp
from textwrap import dedent

from mock import patch
from mockredis import MockRedis
from nose.tools import assert_raises, eq_, ok_
from requests import codes

from cheddar.app import create_app


class TestControllers(object):

    def setup(self):
        self.config_dir = mkdtemp()
        self.config_file = join(self.config_dir, "cheddar.conf")
        self.local_cache_dir = mkdtemp()
        self.remote_cache_dir = mkdtemp()
        self.username = "username"
        self.password = "password"

        with open(self.config_file, "w") as file_:
            file_.write('LOCAL_CACHE_DIR = "{}"\n'.format(self.local_cache_dir))
            file_.write('REMOTE_CACHE_DIR = "{}"\n'.format(self.remote_cache_dir))

        self.previous_config_file = environ.get("CHEDDAR_SETTINGS")
        environ["CHEDDAR_SETTINGS"] = self.config_file

        with patch('cheddar.configure.Redis', MockRedis):
            self.app = create_app(testing=True)

        self.client = self.app.test_client()
        self.use_json = dict(accept="application/json; charset=UTF-8")
        self.use_auth = dict(authorization="Basic {}".format(b64encode("{}:{}".format(self.username,
                                                                                      self.password))))
        self.app.redis.set("cheddar.user.{}".format(self.username), self.password)

    def teardown(self):
        if self.previous_config_file is None:
            del environ["CHEDDAR_SETTINGS"]
        else:
            environ["CHEDDAR_SETTINGS"] = self.previous_config_file

        rmtree(self.local_cache_dir)
        rmtree(self.remote_cache_dir)
        rmtree(self.config_dir)

    def test_index_template_render(self):
        result = self.client.get("/")
        eq_(result.status_code, codes.ok)

    def test_index_template_json(self):
        result = self.client.get("/", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(history=[]))

    def test_get_projects_no_projects_template_render(self):
        result = self.client.get("/simple")
        eq_(result.status_code, codes.ok)

    def test_get_projects_no_project_json(self):
        result = self.client.get("/simple", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(projects=[]))

    def test_get_projects_two_projects_json(self):
        self.app.projects.add_metadata({"name": "foo", "version": "1.0"})
        self.app.projects.add_metadata({"name": "bar", "version": "1.1"})

        result = self.client.get("/simple", headers=self.use_json)
        eq_(result.status_code, codes.ok)
        eq_(loads(result.data), dict(projects=["bar", "foo"]))

    def test_get_project_local_template_render(self):
        self.app.projects.add_metadata({"name": "foo", "version": "1.0", "_filename": "foo-1.0.tar.gz"})
        self.app.projects.add_metadata({"name": "foo", "version": "1.1", "_filename": "foo-1.1.tar.gz"})
        self.app.projects.add_metadata({"name": "foo", "version": "1.0.dev1", "_filename": "foo-1.0.dev1.tar.gz"})

        result = self.client.get("/simple/foo")

        eq_(result.status_code, codes.ok)
        iter_ = self.app.index.remote._iter_version_links(result.data, "http://pypi.python.org/simple")
        eq_(iter_.next(), ("foo-1.1.tar.gz", "/local/foo-1.1.tar.gz"))
        eq_(iter_.next(), ("foo-1.0.tar.gz", "/local/foo-1.0.tar.gz"))
        eq_(iter_.next(), ("foo-1.0.dev1.tar.gz", "/local/foo-1.0.dev1.tar.gz"))
        with assert_raises(StopIteration):
            iter_.next()

    def test_get_project_remote_template_render(self):
        with self._mocked_get("http://pypi.python.org/simple/foo", codes.ok) as mock_get:
            mock_get.return_value.text = dedent("""\
                <html>
{'fraction_non_alphanumeric': 0.1458843704066634, 'fraction_numerical': 0.009554140127388535, 'mean_word_length': 2.979044834307992, 'pattern_counts': {'":': 26, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '225754', 'n_tokens_mistral': 2672, 'n_tokens_neox': 2619, 'n_words': 439}