<commit_before># -*- coding: utf-8 -*-
import json
import os
import tempfile

from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.utils.encoding import smart_unicode

import mock
from nose import SkipTest
from nose.tools import eq_, ok_
from PIL import Image
from pyquery import PyQuery as pq
from tower import strip_whitespace
from waffle.models import Switch

import amo
import amo.tests
from access.models import Group, GroupUser
from addons.models import (Addon, AddonCategory, AddonDeviceType, AddonUser,
                           Category)
from amo.helpers import absolutify
from amo.tests import assert_required, formset, initial
from amo.tests.test_helpers import get_image_path
from amo.urlresolvers import reverse
from devhub.models import ActivityLog
from editors.models import RereviewQueue
from lib.video.tests import files as video_files
from translations.models import Translation
from users.models import UserProfile
from versions.models import Version

import mkt
from mkt.comm.models import CommunicationNote
from mkt.constants import regions
from mkt.site.fixtures import fixture
from mkt.webapps.models import AddonExcludedRegion as AER


response_mock = mock.Mock()
response_mock.read.return_value = '''
    {
        "name": "<NAME>!",
        "description": "Goin' hard in the paint.",
        "launch_path": "/ballin/4.eva",
        "developer": {
            "name": "<NAME>",
            "url": "http://www.ballin4eva.xxx"
        },
        "icons": {
            "128": "/ballin/icon.png"
        },
        "installs_allowed_from": [ "https://marketplace.firefox.com" ]
    }
'''
response_mock.headers = {'Content-Type':
                         'application/x-web-app-manifest+json'}


def get_section_url(addon, section, edit=False):
    args = [addon.app_slug, section]
    if edit:
        args.append('edit')
    return reverse('mkt.developers.apps.section', args=args)


class TestEdit(amo.tests.TestCase):
    fixtures = fixture('group_admin', 'user_999', 'user_admin',
                       'user_admin_group', 'webapp_337141')

    def setUp(self):
        self.webapp = self.get_webapp()
        self.url = self.webapp.get_dev_url()
        self.user = UserProfile.objects.get(username='31337')
        assert self.client.login(username=self.user.email, password='password')

    def get_webapp(self):
        return Addon.objects.no_cache().get(id=337141)

    def get_url(self, section, edit=False):
        return get_section_url(self.webapp, section, edit)

    def get_dict(self, **kw):
        fs = formset(self.cat_initial, initial_count=1)
        result = {'name': 'new name', 'slug': 'test_slug',
                  'description': 'new description'}
        result.update(**kw)
        result.update(fs)
        return result

    def compare(self, data):
        """Compare an app against a `dict` of expected values."""
        mapping = {
            'regions': 'get_region_ids'
        }

        webapp = self.get_webapp()
        for k, v in data.iteritems():
            k = mapping.get(k, k)
            val = getattr(webapp, k, '')
            if callable(val):
                val = val()
            if val is None:
                val = ''

            eq_(unicode(val), unicode(v))

    def compare_features(self, data, version=None):
        """
        Compare an app's set of required features against a `dict` of expected
        values.
        """
        if not version:
            version = self.get_webapp().current_version
        features = version.features
        for k, v in data.iteritems():
            val = getattr(features, k)
            if callable(val):
                val = val()
            eq_(unicode(val), unicode(v))

    def check_form_url(self, section):
        # Check form destinations and "Edit" button.
        r = self.client.get(self.url)
        eq_(r.status_code, 200)
        doc = pq(r.content)
        eq_(doc('form').attr('action'), self.edit_url)
        eq_(doc('h2 .button').attr('data-editurl'), self.edit_url)

        # Check "Cancel" button.
        r = self.client.get(self.edit_url)
        eq_(pq(r.content)('form .addon-edit-cancel').attr('href'), self.url)


class TestEditListingWebapp(TestEdit):
    fixtures = fixture('webapp_337141')

    @mock.patch.object(settings, 'APP_PREVIEW', False)
    def test_apps_context(self):
        r = self.client.get(self.url)
        eq_(r.context['webapp'], True)
        eq_(pq(r.content)('title').text(),
            'Edit Listing | %s | Firefox Marketplace' % self.webapp.name)

    def test_redirect(self):
        r = self.client.get(self.url.replace('edit', ''))
        self.assert3xx(r, self.url)

    def test_nav_links(self):
        r = self.client.get(self.url)
        doc = pq(r.content)('.edit-addon-nav')
        eq_(doc.length, 2)
        eq_(doc('.view-stats').length, 0)

    def test_edit_with_no_current_version(self):
        # Disable file for latest version, and then update app.current_version.
        app = self.get_webapp()
        app.versions.latest().all_files[0].update(status=amo.STATUS_DISABLED)
        app.update_version()

        # Now try to display edit page.
        r = self.client.get(self.url)
        eq_(r.status_code, 200)


@mock.patch.object(settings, 'TASK_USER_ID', 999)
class TestEditBasic(TestEdit):
    fixtures = TestEdit.fixtures

    def setUp(self):
        super(TestEditBasic, self).setUp()
        self.cat = Category.objects.create(name='Games', type=amo.ADDON_WEBAPP)
        self.dtype = DEVICE_TYPES.keys()[0]
        AddonCategory.objects.create(addon=self.webapp, category=self.cat)
        AddonDeviceType.objects.create(addon=self.webapp,
                                       device_type=self.dtype)
        self.url = self.get_url('basic')
        self.edit_url = self.get_url('basic', edit=True)

    def get_webapp(self):
        return Addon.objects.get(id=337141)

    def get_dict(self, **kw):
        result = {'device_types': self.dtype, 'slug': 'NeW_SluG',
                  'description': 'New description with <em>html</em>!',
                  'manifest_url': self.webapp.manifest_url,
                  'categories': [self.cat.id]}
        result.update(**kw)
        return result

    def test_form_url(self):
        self.check_form_url('basic')<commit_msg>fix test error<commit_after># -*- coding: utf-8 -*-
import json
import os
import tempfile

from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.utils.encoding import smart_unicode

import mock
from nose import SkipTest
from nose.tools import eq_, ok_
from PIL import Image
from pyquery import PyQuery as pq
from tower import strip_whitespace
from waffle.models import Switch

import amo
import amo.tests
from access.models import Group, GroupUser
from addons.models import (Addon, AddonCategory, AddonDeviceType, AddonUser,
                           Category)
from amo.helpers import absolutify
from amo.tests import assert_required, formset, initial
from amo.tests.test_helpers import get_image_path
from amo.urlresolvers import reverse
from devhub.models import ActivityLog
from editors.models import RereviewQueue
from lib.video.tests import files as video_files
from translations.models import Translation
from users.models import UserProfile
from versions.models import Version

import mkt
from mkt.comm.models import CommunicationNote
from mkt.constants import regions
from mkt.site.fixtures import fixture
from mkt.webapps.models import AddonExcludedRegion as AER


response_mock = mock.Mock()
response_mock.read.return_value = '''
    {
        "name": "Something Ballin!",
        "description": "Goin' hard in the paint.",
        "launch_path": "/ballin/4.eva",
        "developer": {
            "name": "<NAME>",
            "url": "http://www.ballin4eva.xxx"
        },
        "icons": {
            "128": "/ballin/icon.png"
        },
        "installs_allowed_from": [ "https://marketplace.firefox.com" ]
    }
'''
response_mock.headers = {'Content-Type':
                         'application/x-web-app-manifest+json'}


def get_section_url(addon, section, edit=False):
    args = [addon.app_slug, section]
    if edit:
        args.append('edit')
    return reverse('mkt.developers.apps.section', args=args)


class TestEdit(amo.tests.TestCase):
    fixtures = fixture('group_admin', 'user_999', 'user_admin',
                       'user_admin_group', 'webapp_337141')

    def setUp(self):
        self.webapp = self.get_webapp()
        self.url = self.webapp.get_dev_url()
        self.user = UserProfile.objects.get(username='31337')
        assert self.client.login(username=self.user.email, password='password')

    def get_webapp(self):
        return Addon.objects.no_cache().get(id=337141)

    def get_url(self, section, edit=False):
        return get_section_url(self.webapp, section, edit)

    def get_dict(self, **kw):
        fs = formset(self.cat_initial, initial_count=1)
        result = {'name': 'new name', 'slug': 'test_slug',
                  'description': 'new description'}
        result.update(**kw)
        result.update(fs)
        return result

    def compare(self, data):
        """Compare an app against a `dict` of expected values."""
        mapping = {
            'regions': 'get_region_ids'
        }

        webapp = self.get_webapp()
        for k, v in data.iteritems():
            k = mapping.get(k, k)
            val = getattr(webapp, k, '')
            if callable(val):
                val = val()
            if val is None:
                val = ''

            eq_(unicode(val), unicode(v))

    def compare_features(self, data, version=None):
        """
        Compare an app's set of required features against a `dict` of expected
        values.
        """
        if not version:
            version = self.get_webapp().current_version
        features = version.features
        for k, v in data.iteritems():
            val = getattr(features, k)
            if callable(val):
                val = val()
            eq_(unicode(val), unicode(v))

    def check_form_url(self, section):
        # Check form destinations and "Edit" button.
        r = self.client.get(self.url)
        eq_(r.status_code, 200)
        doc = pq(r.content)
        eq_(doc('form').attr('action'), self.edit_url)
        eq_(doc('h2 .button').attr('data-editurl'), self.edit_url)

        # Check "Cancel" button.
        r = self.client.get(self.edit_url)
        eq_(pq(r.content)('form .addon-edit-cancel').attr('href'), self.url)


class TestEditListingWebapp(TestEdit):
    fixtures = fixture('webapp_337141')

    @mock.patch.object(settings, 'APP_PREVIEW', False)
    def test_apps_context(self):
        r = self.client.get(self.url)
        eq_(r.context['webapp'], True)
        eq_(pq(r.content)('title').text(),
            'Edit Listing | %s | Firefox Marketplace' % self.webapp.name)

    def test_redirect(self):
        r = self.client.get(self.url.replace('edit', ''))
        self.assert3xx(r, self.url)

    def test_nav_links(self):
        r = self.client.get(self.url)
        doc = pq(r.content)('.edit-addon-nav')
        eq_(doc.length, 2)
        eq_(doc('.view-stats').length, 0)

    def test_edit_with_no_current_version(self):
        # Disable file for latest version, and then update app.current_version.
        app = self.get_webapp()
        app.versions.latest().all_files[0].update(status=amo.STATUS_DISABLED)
        app.update_version()

        # Now try to display edit page.
        r = self.client.get(self.url)
        eq_(r.status_code, 200)


@mock.patch.object(settings, 'TASK_USER_ID', 999)
class TestEditBasic(TestEdit):
    fixtures = TestEdit.fixtures

    def setUp(self):
        super(TestEditBasic, self).setUp()
        self.cat = Category.objects.create(name='Games', type=amo.ADDON_WEBAPP)
        self.dtype = amo.DEVICE_TYPES.keys()[0]
        AddonCategory.objects.create(addon=self.webapp, category=self.cat)
        AddonDeviceType.objects.create(addon=self.webapp,
                                       device_type=self.dtype)
        self.url = self.get_url('basic')
        self.edit_url = self.get_url('basic', edit=True)

    def get_webapp(self):
        return Addon.objects.get(id=337141)

    def get_dict(self, **kw):
        result = {'device_types': self.dtype, 'slug': 'NeW_SluG',
                  'description': 'New description with <em>html</em>!',
                  'manifest_url': self.webapp.manifest_url,
                  'categories': [self.cat.id]}
        result.update(**kw)
        return result

    def test_form_url(self):
        self.check_form_url('basic')
{'fraction_non_alphanumeric': 0.12190909804537248, 'fraction_numerical': 0.008477902504121202, 'mean_word_length': 2.587721768515911, 'pattern_counts': {'":': 18, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, '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': '3818169', 'n_tokens_mistral': 4022, 'n_tokens_neox': 3871, 'n_words': 882}