Exemplo n.º 1
0
 def _permissions(self):
     permissions = Permission.objects.all()
     self.permission_relation = []
     for permission in permissions:
         right_name = "%s.%s" % (
             permission.content_type.app_label, permission.codename)
         if right_name in PERMISSION_CODENAMES.keys():
             perm_value = PERMISSION_CODENAMES[right_name]
             if isinstance(perm_value[0], six.text_type):
                 perm_value = [perm_value]
             rigth_id = None
             for rigth_name, ext_name in perm_value:
                 cur = self.old_db.open()
                 sql_text = six.text_type("SELECT R.id FROM CORE_extension_rights R,CORE_extension E WHERE R.extension=E.id AND R.description='%s' AND E.extensionId='%s'") % (
                     six.text_type(rigth_name), ext_name)
                 try:
                     cur.execute(sql_text)
                 except:
                     self.print_debug("SQL error:%s", sql_text)
                 rigth_id = cur.fetchone()
                 if rigth_id is not None:
                     break
             if rigth_id is not None:
                 self.permission_relation.append(
                     (permission.id, rigth_id[0]))
             else:
                 self.print_debug("=> not found %s", (sql_text,))
Exemplo n.º 2
0
 def test_overriding_prefetch(self):
     with self.assertNumQueries(3):
         qs = Author.objects.prefetch_related('books', 'books__read_by')
         lists = [[[six.text_type(r) for r in b.read_by.all()]
                   for b in a.books.all()]
                  for a in qs]
         self.assertEqual(lists,
         [
             [["Amy"], ["Belinda"]],  # Charlotte - Poems, Jane Eyre
             [["Amy"]],                # Anne - Poems
             [["Amy"], []],            # Emily - Poems, Wuthering Heights
             [["Amy", "Belinda"]],    # Jane - Sense and Sense
         ])
     with self.assertNumQueries(3):
         qs = Author.objects.prefetch_related('books__read_by', 'books')
         lists = [[[six.text_type(r) for r in b.read_by.all()]
                   for b in a.books.all()]
                  for a in qs]
         self.assertEqual(lists,
         [
             [["Amy"], ["Belinda"]],  # Charlotte - Poems, Jane Eyre
             [["Amy"]],                # Anne - Poems
             [["Amy"], []],            # Emily - Poems, Wuthering Heights
             [["Amy", "Belinda"]],    # Jane - Sense and Sense
         ])
Exemplo n.º 3
0
 def __init__(self, var_node, **kwargs):
     super(BaseVariableContextFinding, self).__init__(**kwargs)
     self._var_node = var_node
     self._line_number = kwargs.get('line_number')
     self._filename = six.text_type(kwargs.get('filename'))
     self._vulnerability_text = six.text_type(
         kwargs.get('vulnerability_text'))
    def test_initial(self):
        relation0 = self.model.objects.create(name='relation0' + self.id())
        relation1 = self.model.objects.create(name='relation1' + self.id())
        fixture = self.model.objects.create(name=self.id())
        self.add_relations(fixture, [relation0, relation1])

        # Instanciate the modelform for that instance
        form = self.form(instance=fixture)

        # Ensure that the widget rendered right, with only the selection
        self.assertHTMLEqual(
            forms.SelectMultiple(
                choices=(
                    (self.get_value(relation0), six.text_type(relation0)),
                    (self.get_value(relation1), six.text_type(relation1)),
                ),
                attrs={
                    'data-autocomplete-light-function': 'select2',
                    'data-autocomplete-light-url': reverse(self.url_name),
                    'id': 'id_test',
                }
            ).render('test', value=[
                self.get_value(relation0),
                self.get_value(relation1),
            ]),
            six.text_type(form['test'].as_widget())
        )
Exemplo n.º 5
0
    def test_abstract(self):
        # The Student and Worker models both have 'name' and 'age' fields on
        # them and inherit the __str__() method, just as with normal Python
        # subclassing. This is useful if you want to factor out common
        # information for programming purposes, but still completely
        # independent separate models at the database level.
        w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
        Worker.objects.create(name="Barney", age=34, job="Quarry worker")

        s = Student.objects.create(name="Pebbles", age=5, school_class="1B")

        self.assertEqual(six.text_type(w1), "Worker Fred")
        self.assertEqual(six.text_type(s), "Student Pebbles")

        # The children inherit the Meta class of their parents (if they don't
        # specify their own).
        self.assertQuerysetEqual(Worker.objects.values("name"), [{"name": "Barney"}, {"name": "Fred"}], lambda o: o)

        # Since Student does not subclass CommonInfo's Meta, it has the effect
        # of completely overriding it. So ordering by name doesn't take place
        # for Students.
        self.assertEqual(Student._meta.ordering, [])

        # However, the CommonInfo class cannot be used as a normal model (it
        # doesn't exist as a model).
        with self.assertRaises(AttributeError):
            CommonInfo.objects.all()
Exemplo n.º 6
0
    def list_dir(self, path):
        """Lists the contents of the specified path.

        The result will be an ordered dictionary of contents, mapping
        filenames or directory names with a dictionary containing:

        * ``path``        - The full path of the file or directory.
        * ``created_rev`` - The revision where the file or directory was
                            created.
        """
        result = SortedDict()

        if api_version()[:2] >= (1, 5):
            depth = 2  # Immediate files in this path. Only in 1.5+.
        else:
            depth = 0  # This will trigger recurse=False for SVN < 1.5.

        dirents = self.client.list(B(self.normalize_path(path)), None, depth)

        for name, dirent in six.iteritems(dirents):
            if name:
                result[six.text_type(name)] = {
                    'path': '%s/%s' % (path.strip('/'), name),
                    'created_rev': six.text_type(dirent['created_rev']),
                }

        return result
def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        name = six.text_type(value.obj)
        return mark_safe('<a href=%s>%s</a>' % (value, escape(name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template('rest_framework/admin/list_value.html')
        else:
            template = loader.get_template('rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, six.string_types):
        if (
            (value.startswith('http:') or value.startswith('https:')) and not
            re.search(r'\s', value)
        ):
            return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value)
Exemplo n.º 8
0
 def date_error_message(self, lookup_type, field, unique_for):
     opts = self._meta
     return _("%(field_name)s must be unique for %(date_field)s %(lookup)s.") % {
         'field_name': six.text_type(capfirst(opts.get_field(field).verbose_name)),
         'date_field': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
         'lookup': lookup_type,
     }
 def test_tag_render(self):
     "Check unicode tag name renders"
     t1 = self.model.objects.get(name="Test")
     tags = list(t1.tags.all())
     self.assertEqual(six.text_type(tags[0]), 'boy')
     self.assertEqual(six.text_type(tags[1]), 'niño')
     self.assertEqual(six.text_type(tags[2]), '男の子')
Exemplo n.º 10
0
    def get_gateway_url(self, request):
        "Routes a payment to Gateway, should return URL for redirection."
        params = {
            'id': self.get_backend_setting('id'),
            'opis': self.get_order_description(self.payment,
                                               self.payment.order),
            # Here we put payment.pk as we can get order through payment model
            'crc': self.payment.pk,
            # amount is  in format XXX.YY PLN
            'kwota': text_type(self.payment.amount),
        }

        self._build_user_data(params)
        self._build_md5sum(params)
        self._build_urls(params)

        method = self.get_backend_setting('method', 'get').lower()
        if method not in ('post', 'get'):
            raise ImproperlyConfigured(
                'Transferuj.pl payment backend accepts only GET or POST'
            )

        if method == 'post':
            return (self._GATEWAY_URL, 'POST', params)

        params = {k: text_type(v).encode('utf-8') for k, v in params.items()}
        return (
            "{}?{}".format(self._GATEWAY_URL, urlencode(params)),
            "GET",
            {}
        )
 def test_delete_decreases_correct(self):
     """
     Check that the actual tag in the database is decreased, not the one in
     the instance at time of deletion
     """
     t1 = test_models.SingleTagFieldModel.objects.create(name='Test 1', title='Mr')
     t2 = test_models.SingleTagFieldModel.objects.create(name='Test 2', title='Mrs')
     self.assertEqual(six.text_type(t1.title.name), 'Mr')
     self.assertEqual(six.text_type(t2.title.name), 'Mrs')
     self.assertTagModel(self.tag_model, {
         'Mr': 1,
         'Mrs': 1,
     })
     
     # Now change the title and delete without saving
     t1.title = 'Mrs'
     self.assertEqual(six.text_type(t1.title.name), 'Mrs')
     self.assertTagModel(self.tag_model, {
         'Mr': 1,
         'Mrs': 1,
     })
     t1.delete()
     
     # Check the original tag 'Mr' was decremented (and deleted)
     self.assertTagModel(self.tag_model, {
         'Mrs': 1,
     })
     
     # But check that tagulous still thinks the tag is 'Mrs'
     self.assertEqual(six.text_type(t1.title.name), 'Mrs')
    def test_view_get(self):
        self.login(usertype="staff")

        # first access via .get() -> returned the default value "initial value"
        url = reverse("test_user_settings",
            kwargs={"test_name": "get", "key": "Foo", "value": "initial value"}
        )
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)
        self.failUnlessEqual(six.text_type(response.content, "UTF-8"), "initial value")

        # change with .setitem()
        url = reverse("test_user_settings",
            kwargs={"test_name": "setitem", "key": "Foo", "value": "new value"}
        )
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)
        self.failUnlessEqual(six.text_type(response.content, "UTF-8"), "new value")

        # now, the .get() method should returned the current value
        url = reverse("test_user_settings",
            kwargs={"test_name": "get", "key": "Foo", "value": "initial value"}
        )
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)
        self.failUnlessEqual(six.text_type(response.content, "UTF-8"), "new value")
Exemplo n.º 13
0
 def compute_sig(params, fields, key):
     text = u''
     for field in fields:
         text += text_type(params.get(field, ''))
     text += key
     text_encoded = text.encode('utf-8')
     return text_type(hashlib.md5(text_encoded).hexdigest())
Exemplo n.º 14
0
    def _make_token_with_timestamp(self, user, timestamp):
        # timestamp is number of days since 2001-1-1.  Converted to
        # base 36, this gives us a 3 digit string until about 2121
        ts_b36 = int_to_base36(timestamp)

        # By hashing on the internal state of the user and using state
        # that is sure to change (the password salt will change as soon as
        # the password is set, at least for current Django auth, and
        # last_login will also change), we produce a hash that will be
        # invalid as soon as it is used.
        # We limit the hash to 20 chars to keep URL short
        key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"

        # Ensure results are consistent across DB backends
        user_last_login = UserLastLogin.objects.get_by_username(user.username)
        if user_last_login is None:
            from seahub.utils.timeutils import dt
            login_dt = dt(user.ctime)
        else:
            login_dt = user_last_login.last_login
        login_timestamp = login_dt.replace(microsecond=0, tzinfo=None)

        value = (six.text_type(user.id) + user.enc_password +
                 six.text_type(login_timestamp) + six.text_type(timestamp))
        hash = salted_hmac(key_salt, value).hexdigest()[::2]
        return "%s-%s" % (ts_b36, hash)
Exemplo n.º 15
0
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if strings_only and (s is None or isinstance(s, int)):
        return s
    if isinstance(s, Promise):
        return six.text_type(s).encode(encoding, errors)
    if not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([force_bytes(arg, encoding, strings_only,
                        errors) for arg in s])
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors)
Exemplo n.º 16
0
    def test_listing(self):
        self.factory.xfer = ChartsAccountListing()
        self.call(
            "/diacamma.accounting/chartsAccountListing",
            {"year": "1", "type_of_account": "-1", "PRINT_MODE": "4", "MODEL": 6},
            False,
        )
        self.assert_observer("core.print", "diacamma.accounting", "chartsAccountListing")
        csv_value = b64decode(six.text_type(self.get_first_xpath("PRINT").text)).decode("utf-8")
        content_csv = csv_value.split("\n")
        self.assertEqual(len(content_csv), 22, str(content_csv))
        self.assertEqual(content_csv[1].strip(), '"Liste de plan comptable"')
        self.assertEqual(
            content_csv[3].strip(), '"code";"nom";"total de l\'exercice précédent";"total exercice";"total validé";'
        )
        self.assertEqual(
            content_csv[4].strip(), '"106";"106";"Crédit: 1250.38€";"Crédit: 1250.38€";"Crédit: 1250.38€";'
        )
        self.assertEqual(content_csv[9].strip(), '"512";"512";"Débit: 1135.93€";"Débit: 1130.29€";"Débit: 1130.29€";')
        self.assertEqual(content_csv[10].strip(), '"531";"531";"Débit: 114.45€";"Crédit: 79.63€";"Débit: 114.45€";')

        self.factory.xfer = ChartsAccountListing()
        self.call(
            "/diacamma.accounting/chartsAccountListing",
            {"year": "1", "type_of_account": "4", "PRINT_MODE": "4", "MODEL": 6},
            False,
        )
        self.assert_observer("core.print", "diacamma.accounting", "chartsAccountListing")
        csv_value = b64decode(six.text_type(self.get_first_xpath("PRINT").text)).decode("utf-8")
        content_csv = csv_value.split("\n")
        self.assertEqual(len(content_csv), 12, str(content_csv))
Exemplo n.º 17
0
def delete(request, extra_context=None, next_override=None, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    delete_avatar_form = DeleteAvatarForm(request.POST or None,
                                          user=request.user,
                                          avatars=avatars)
    if request.method == 'POST':
        if delete_avatar_form.is_valid():
            ids = delete_avatar_form.cleaned_data['choices']
            if six.text_type(avatar.id) in ids and avatars.count() > len(ids):
                # Find the next best avatar, and set it as the new primary
                for a in avatars:
                    if six.text_type(a.id) not in ids:
                        a.primary = True
                        a.save()
                        avatar_updated.send(sender=Avatar, user=request.user,
                                            avatar=avatar)
                        break
            Avatar.objects.filter(id__in=ids).delete()
            messages.success(request,
                             _("Successfully deleted the requested avatars."))
            return redirect(next_override or _get_next(request))

    context = {
        'avatar': avatar,
        'avatars': avatars,
        'delete_avatar_form': delete_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)

    return render(request, 'avatar/confirm_delete.html', context)
Exemplo n.º 18
0
 def render(self, context):
     field = self.field.resolve(context)
     if "." not in self.field_name:
         verbose_name = six.text_type(context[self.field_name]._meta.verbose_name)
     else:
         instance, field_name = self.field_name.rsplit(".", 1)
         model = context[instance].__class__
         model_field = model._meta.get_field(field_name)
         verbose_name = six.text_type(model_field.verbose_name)
         if self.unit is None:
             try:
                 self.unit = model_field.unit
             except AttributeError:
                 pass
     verbose_name = jb_common.utils.base.capitalize_first_letter(verbose_name)
     if self.unit == "yes/no":
         field = jb_common.templatetags.juliabase.fancy_bool(field)
         unit = None
     elif self.unit == "user":
         field = get_really_full_name(field, autoescape=True)
         unit = None
     elif self.unit == "sccm_collapse":
         if not field:
             return """<td colspan="2"></td>"""
         unit = "sccm"
     elif not field and field != 0:
         unit = None
         field = "—"
     else:
         unit = self.unit
     if self.significant_digits and field != "—":
         field = jb_common.utils.base.round(field, self.significant_digits)
     return """<td class="field-label">{label}:</td><td class="field-value">{value}</td>""".format(
         label=verbose_name, value=conditional_escape(field) if unit is None else quantity(field, unit))
Exemplo n.º 19
0
    def test_abstract(self):
        # The Student and Worker models both have 'name' and 'age' fields on
        # them and inherit the __unicode__() method, just as with normal Python
        # subclassing. This is useful if you want to factor out common
        # information for programming purposes, but still completely
        # independent separate models at the database level.
        w1 = Worker.objects.create(name="Fred", age=35, job="Quarry worker")
        w2 = Worker.objects.create(name="Barney", age=34, job="Quarry worker")

        s = Student.objects.create(name="Pebbles", age=5, school_class="1B")

        self.assertEqual(six.text_type(w1), "Worker Fred")
        self.assertEqual(six.text_type(s), "Student Pebbles")

        # The children inherit the Meta class of their parents (if they don't
        # specify their own).
        self.assertQuerysetEqual(
            Worker.objects.values("name"), [
                {"name": "Barney"},
                {"name": "Fred"},
            ],
            lambda o: o
        )

        # Since Student does not subclass CommonInfo's Meta, it has the effect
        # of completely overriding it. So ordering by name doesn't take place
        # for Students.
        self.assertEqual(Student._meta.ordering, [])

        # However, the CommonInfo class cannot be used as a normal model (it
        # doesn't exist as a model).
        self.assertRaises(AttributeError, lambda: CommonInfo.objects.all())

        # A StudentWorker which does not exist is both a Student and Worker
        # which does not exist.
        self.assertRaises(Student.DoesNotExist,
            StudentWorker.objects.get, pk=12321321
        )
        self.assertRaises(Worker.DoesNotExist,
            StudentWorker.objects.get, pk=12321321
        )

        # MultipleObjectsReturned is also inherited.
        # This is written out "long form", rather than using __init__/create()
        # because of a bug with diamond inheritance (#10808)
        sw1 = StudentWorker()
        sw1.name = "Wilma"
        sw1.age = 35
        sw1.save()
        sw2 = StudentWorker()
        sw2.name = "Betty"
        sw2.age = 24
        sw2.save()

        self.assertRaises(Student.MultipleObjectsReturned,
            StudentWorker.objects.get, pk__lt=sw2.pk + 100
        )
        self.assertRaises(Worker.MultipleObjectsReturned,
            StudentWorker.objects.get, pk__lt=sw2.pk + 100
        )
Exemplo n.º 20
0
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and (s is None or isinstance(s, int)):
        return s
    if isinstance(s, Promise):
        return six.text_type(s).encode(encoding, errors)
    elif not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([smart_str(arg, encoding, strings_only,
                        errors) for arg in s])
            return six.text_type(s).encode(encoding, errors)
    elif isinstance(s, six.text_type):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s
Exemplo n.º 21
0
Arquivo: test.py Projeto: povtux/core
 def assert_coordcomp_equal(self, xpath, coord):
     self.assert_attrib_equal(xpath, "x", six.text_type(coord[0]))
     self.assert_attrib_equal(xpath, "y", six.text_type(coord[1]))
     self.assert_attrib_equal(xpath, "colspan", six.text_type(coord[2]))
     self.assert_attrib_equal(xpath, "rowspan", six.text_type(coord[3]))
     if len(coord) > 4:
         self.assert_attrib_equal(xpath, "tab", six.text_type(coord[4]))
Exemplo n.º 22
0
    def test_sidebar(self):
        """Testing submitter view sidebar"""
        user = User.objects.get(username='******')
        user.review_groups.clear()

        group1 = Group.objects.create(name='test-group-1')
        group1.users.add(user)

        group2 = Group.objects.create(name='test-group-2', invite_only=True)
        group2.users.add(user)

        # Now load the page and get the sidebar items.
        response = self.client.get('/users/grumpy/')
        self.assertEqual(response.status_code, 200)

        datagrid = self._get_context_var(response, 'datagrid')
        self.assertIsNotNone(datagrid)

        sidebar_items = \
            self._get_context_var(response, 'datagrid').sidebar_items
        self.assertEqual(len(sidebar_items), 2)

        # Test the User Profile section.
        section = sidebar_items[0]
        self.assertIsInstance(section, UserProfileItem)

        # Test the Groups section.
        section = sidebar_items[1]
        self.assertIsInstance(section, UserGroupsItem)
        self.assertEqual(six.text_type(section.label), 'Groups')
        self.assertEqual(len(section.items), 1)
        self.assertEqual(six.text_type(section.items[0].label),
                         'test-group-1')
    def setup_basic_post_test(self, user, with_local_site, local_site_name,
                              post_valid_data):
        if post_valid_data:
            self.create_review_group(name='group1',
                                     with_local_site=with_local_site)
            self.create_review_group(name='group2',
                                     with_local_site=with_local_site)
            repo1 = self.create_repository(name='Test Repo 1',
                                           with_local_site=with_local_site,
                                           path='test-repo-1')
            repo2 = self.create_repository(name='Test Repo 2',
                                           with_local_site=with_local_site,
                                           path='test-repo-2')

            if with_local_site:
                site = self.get_local_site(name=local_site_name)
                site.users.add(User.objects.get(username='******'))
                site.users.add(User.objects.get(username='******'))

            post_data = {
                'name': 'my-default',
                'file_regex': '.*',
                'users': 'doc,dopey',
                'groups': 'group1,group2',
                'repositories': ','.join([six.text_type(repo1.pk),
                                          six.text_type(repo2.pk)]),
            }
        else:
            post_data = {}

        return (get_default_reviewer_list_url(local_site_name),
                default_reviewer_item_mimetype,
                post_data,
                [local_site_name])
Exemplo n.º 24
0
    def test_initial(self):
        tag = self.tag.objects.create(name='tag' + self.id())
        fixture = self.model.objects.create(name=self.id())
        fixture.test.add(tag)

        # Instanciate the modelform for that instance
        form = self.form(instance=fixture)

        # Ensure that the widget rendered right, with only the selection
        self.assertHTMLEqual(
            forms.SelectMultiple(
                choices=(
                    (six.text_type(tag), six.text_type(tag)),
                ),
                attrs={
                    'data-autocomplete-light-function': 'select2',
                    'data-autocomplete-light-url': reverse(self.url_name),
                    'data-tags': 1,
                    'id': 'id_test',
                }
            ).render('test', value=[
                six.text_type(tag),
            ]),
            six.text_type(form['test'].as_widget())
        )
Exemplo n.º 25
0
Arquivo: tests.py Projeto: 10sr/hue
    def test_change_form_deletion_when_invalid(self):
        """
        Make sure that a change form that is filled out, but marked for deletion
        doesn't cause validation errors.
        """
        PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__all__")
        poet = Poet.objects.create(name='test')
        poem = poet.poem_set.create(name='test poem')
        data = {
            'poem_set-TOTAL_FORMS': '1',
            'poem_set-INITIAL_FORMS': '1',
            'poem_set-MAX_NUM_FORMS': '0',
            'poem_set-0-id': six.text_type(poem.id),
            'poem_set-0-poem': six.text_type(poem.id),
            'poem_set-0-name': 'x' * 1000,
        }
        formset = PoemFormSet(data, instance=poet)
        # Make sure this form doesn't pass validation.
        self.assertEqual(formset.is_valid(), False)
        self.assertEqual(Poem.objects.count(), 1)

        # Then make sure that it *does* pass validation and delete the object,
        # even though the data isn't actually valid.
        data['poem_set-0-DELETE'] = 'on'
        formset = PoemFormSet(data, instance=poet)
        self.assertEqual(formset.is_valid(), True)
        formset.save()
        self.assertEqual(Poem.objects.count(), 0)
    def test_form(self, mock_randint, mock_hash_answer, mock_get_operator):

        ops = ['+', '-']
        ints = [1, 3, 1, 3]
        mock_randint.side_effect = lambda x, y: ints.pop(0)
        mock_hash_answer.side_effect = lambda x: "answer=%s" % x
        mock_get_operator.side_effect = lambda: ops.pop(0)

        class F(forms.Form):
            captcha = MathCaptchaField()

        f = F()
        result1 = six.text_type(f)
        result2 = six.text_type(f)
        self.assertHTMLEqual(result1, """
            <tr><th><label for="id_captcha_0">Captcha:</label></th><td>
                <span class="captcha-question">What is 1 + 3?</span>
                <input id="id_captcha_0" required name="captcha_0"
                       size="5" type="text" />
                <input id="id_captcha_1" required name="captcha_1"
                       type="hidden" value="answer=4" />
            </td></tr>""")

        self.assertHTMLEqual(result2, """
            <tr><th><label for="id_captcha_0">Captcha:</label></th><td>
                <span class="captcha-question">What is 3 - 1?</span>
                <input id="id_captcha_0" required name="captcha_0"
                       size="5" type="text" />
                <input id="id_captcha_1" required name="captcha_1"
                       type="hidden" value="answer=2" />
            </td></tr>""")
Exemplo n.º 27
0
    def accept_payment(self, session_id):
        params = {
            'pos_id': PaymentProcessor.get_backend_setting('pos_id'),
            'session_id': session_id,
            'ts': time.time()
        }
        key1 = PaymentProcessor.get_backend_setting('key1')
        key2 = PaymentProcessor.get_backend_setting('key2')
        params['sig'] = PaymentProcessor.compute_sig(
            params, self._GET_SIG_FIELDS, key1)
        for key in params.keys():
            params[key] = six.text_type(params[key]).encode('utf-8')
        data = six.text_type(urlencode(params)).encode('utf-8')
        url = self._GATEWAY_URL + 'UTF/Payment/confirm/txt'
        request = Request(url, data)
        response = urlopen(request)
        response_data = response.read().decode('utf-8')
        response_params = PaymentProcessor._parse_text_response(response_data)
        if response_params['status'] == 'OK':
            if PaymentProcessor.compute_sig(
                    response_params,
                    self._GET_ACCEPT_SIG_FIELDS, key2) != response_params['trans_sig']:
                logger.error(u'Wrong signature for Payment/confirm response: %s' % response_params)
                return
            if int(response_params['trans_pos_id']) != int(params['pos_id']):
                logger.error(u'Wrong pos_id for Payment/confirm response: %s' % response_params)
                return

            logger.info(u'Payment accepted: %s' % response_params)
        else:
            logger.warning(u'Payment not accepted, error: %s' % response_params)
    def test_admin_edits_field(self):
        """admin form allows admins to edit field"""
        response = self.client.post(
            self.test_link,
            data={
                'username': '******',
                'rank': six.text_type(self.user.rank_id),
                'roles': six.text_type(self.user.roles.all()[0].pk),
                'email': '*****@*****.**',
                'twitter': 'lorem_ipsum',
                'new_password': '',
                'signature': '',
                'is_signature_locked': '0',
                'is_hiding_presence': '0',
                'limits_private_thread_invites_to': '0',
                'signature_lock_staff_message': '',
                'signature_lock_user_message': '',
                'subscribe_to_started_threads': '2',
                'subscribe_to_replied_threads': '2',
            }
        )
        self.assertEqual(response.status_code, 302)

        self.reload_user()
        self.assertEqual(self.user.profile_fields['twitter'], 'lorem_ipsum')
Exemplo n.º 29
0
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_text(obj)

        elif isinstance(obj, datetime.timedelta):
            return six.text_type(total_seconds(obj))
 
        elif isinstance(obj, decimal.Decimal):
            # Serializers will coerce decimals to strings by default.
            return float(obj)
 
        elif isinstance(obj, uuid.UUID):
            return six.text_type(obj)
 
        elif isinstance(obj, QuerySet):
            return tuple(obj)
        elif hasattr(obj, 'tolist'):
            # Numpy arrays and array scalars.
            return obj.tolist()

        elif hasattr(obj, '__getitem__'):
            try:
                return dict(obj)
            except:
                pass
        elif hasattr(obj, '__iter__'):
            return tuple(item for item in obj)

        return super(JSONEncoder, self).default(obj)
Exemplo n.º 30
0
    def render_to_response(self, methods, basket):
        pairs = [
            ('METHOD', 'CallbackResponse'),
            ('CURRENCYCODE', self.request.POST.get('CURRENCYCODE', 'GBP')),
        ]
        for index, method in enumerate(methods):
            if hasattr(method, 'set_basket'):
                # Oscar < 0.8
                method.set_basket(basket)
                charge = method.charge_incl_tax
            else:
                cost = method.calculate(basket)
                charge = cost.incl_tax

            pairs.append(('L_SHIPPINGOPTIONNAME%d' % index,
                          six.text_type(method.name)))
            pairs.append(('L_SHIPPINGOPTIONLABEL%d' % index,
                          six.text_type(method.name)))
            pairs.append(('L_SHIPPINGOPTIONAMOUNT%d' % index, charge))
            # For now, we assume tax and insurance to be zero
            pairs.append(('L_TAXAMT%d' % index, D('0.00')))
            pairs.append(('L_INSURANCEAMT%d' % index, D('0.00')))
            # We assume that the first returned method is the default one
            pairs.append(('L_SHIPPINGOPTIONISDEFAULT%d' % index, 1 if index == 0 else 0))
        else:
            # No shipping methods available - we flag this up to PayPal indicating that we
            # do not ship to the shipping address.
            pairs.append(('NO_SHIPPING_OPTION_DETAILS', 1))
        payload = urlencode(pairs)
        return HttpResponse(payload)
Exemplo n.º 31
0
 def test_initial(self):
     form = self.EnumForm(initial={'choice': MyEnum.bar})
     html = six.text_type(form['choice'])
     self.assertInHTML('<option value="bar" selected>Bar</option>', html)
Exemplo n.º 32
0
 def as_p(self):
     "Returns this formset rendered as HTML <p>s."
     forms = ' '.join(form.as_p() for form in self)
     return mark_safe('\n'.join(
         [six.text_type(self.management_form), forms]))
Exemplo n.º 33
0
 def __str__(self):
     return six.text_type(self.exc)
Exemplo n.º 34
0
    def get_initkwargs(cls, form_list=None, initial_dict=None,
        instance_dict=None, condition_dict=None, *args, **kwargs):
        """
        Creates a dict with all needed parameters for the form wizard instances.

        * `form_list` - is a list of forms. The list entries can be single form
          classes or tuples of (`step_name`, `form_class`). If you pass a list
          of forms, the wizardview will convert the class list to
          (`zero_based_counter`, `form_class`). This is needed to access the
          form for a specific step.
        * `initial_dict` - contains a dictionary of initial data dictionaries.
          The key should be equal to the `step_name` in the `form_list` (or
          the str of the zero based counter - if no step_names added in the
          `form_list`)
        * `instance_dict` - contains a dictionary whose values are model
          instances if the step is based on a ``ModelForm`` and querysets if
          the step is based on a ``ModelFormSet``. The key should be equal to
          the `step_name` in the `form_list`. Same rules as for `initial_dict`
          apply.
        * `condition_dict` - contains a dictionary of boolean values or
          callables. If the value of for a specific `step_name` is callable it
          will be called with the wizardview instance as the only argument.
          If the return value is true, the step's form will be used.
        """

        kwargs.update({
            'initial_dict': initial_dict or kwargs.pop('initial_dict',
                getattr(cls, 'initial_dict', None)) or {},
            'instance_dict': instance_dict or kwargs.pop('instance_dict',
                getattr(cls, 'instance_dict', None)) or {},
            'condition_dict': condition_dict or kwargs.pop('condition_dict',
                getattr(cls, 'condition_dict', None)) or {}
        })

        form_list = form_list or kwargs.pop('form_list',
            getattr(cls, 'form_list', None)) or []

        computed_form_list = OrderedDict()

        assert len(form_list) > 0, 'at least one form is needed'

        # walk through the passed form list
        for i, form in enumerate(form_list):
            if isinstance(form, (list, tuple)):
                # if the element is a tuple, add the tuple to the new created
                # sorted dictionary.
                computed_form_list[six.text_type(form[0])] = form[1]
            else:
                # if not, add the form with a zero based counter as unicode
                computed_form_list[six.text_type(i)] = form

        # walk through the new created list of forms
        for form in six.itervalues(computed_form_list):
            if issubclass(form, formsets.BaseFormSet):
                # if the element is based on BaseFormSet (FormSet/ModelFormSet)
                # we need to override the form variable.
                form = form.form
            # check if any form contains a FileField, if yes, we need a
            # file_storage added to the wizardview (by subclassing).
            for field in six.itervalues(form.base_fields):
                if (isinstance(field, forms.FileField) and
                        not hasattr(cls, 'file_storage')):
                    raise NoFileStorageConfigured(
                            "You need to define 'file_storage' in your "
                            "wizard view in order to handle file uploads.")

        # build the kwargs for the wizardview instances
        kwargs['form_list'] = computed_form_list
        return kwargs
Exemplo n.º 35
0
 def _get_position_from_instance(self, instance, ordering):
     attr = getattr(instance, ordering[0].lstrip('-'))
     return six.text_type(attr)
class TestModuleStoreSerializer(TestDumpToNeo4jCommandBase):
    """
    Tests for the ModuleStoreSerializer
    """
    @classmethod
    def setUpClass(cls):
        """Any ModuleStore course/content operations can go here."""
        super(TestModuleStoreSerializer, cls).setUpClass()
        cls.mss = ModuleStoreSerializer.create()

    def test_serialize_item(self):
        """
        Tests the serialize_item method.
        """
        fields, label = serialize_item(self.course)
        self.assertEqual(label, "course")
        self.assertIn("edited_on", fields.keys())
        self.assertIn("display_name", fields.keys())
        self.assertIn("org", fields.keys())
        self.assertIn("course", fields.keys())
        self.assertIn("run", fields.keys())
        self.assertIn("course_key", fields.keys())
        self.assertIn("location", fields.keys())
        self.assertIn("block_type", fields.keys())
        self.assertIn("detached", fields.keys())
        self.assertNotIn("checklist", fields.keys())

    def test_serialize_course(self):
        """
        Tests the serialize_course method.
        """
        nodes, relationships = serialize_course(self.course.id)
        self.assertEqual(len(nodes), 9)
        # the course has 7 "PARENT_OF" relationships and 3 "PRECEDES"
        self.assertEqual(len(relationships), 10)

    def test_strip_version_and_branch(self):
        """
        Tests that the _strip_version_and_branch function strips the version
        and branch from a location
        """
        location = self.course.id.make_usage_key(
            'test_block_type', 'test_block_id').for_branch(
                'test_branch').for_version('test_version')

        self.assertIsNotNone(location.branch)
        self.assertIsNotNone(location.version_guid)

        stripped_location = strip_branch_and_version(location)

        self.assertIsNone(stripped_location.branch)
        self.assertIsNone(stripped_location.version_guid)

    @staticmethod
    def _extract_relationship_pairs(relationships, relationship_type):
        """
        Extracts a list of XBlock location tuples from a list of Relationships.

        Arguments:
            relationships: list of py2neo `Relationship` objects
            relationship_type: the type of relationship to filter `relationships`
              by.
        Returns:
            List of tuples of the locations of of the relationships'
              constituent nodes.
        """
        relationship_pairs = [
            tuple([node["location"] for node in rel.nodes()])
            for rel in relationships if rel.type() == relationship_type
        ]
        return relationship_pairs

    @staticmethod
    def _extract_location_pair(xblock1, xblock2):
        """
        Returns a tuple of locations from two XBlocks.

        Arguments:
            xblock1: an xblock
            xblock2: also an xblock

        Returns:
            A tuple of the string representations of those XBlocks' locations.
        """
        return (six.text_type(xblock1.location),
                six.text_type(xblock2.location))

    def assertBlockPairIsRelationship(self, xblock1, xblock2, relationships,
                                      relationship_type):
        """
        Helper assertion that a pair of xblocks have a certain kind of
        relationship with one another.
        """
        relationship_pairs = self._extract_relationship_pairs(
            relationships, relationship_type)
        location_pair = self._extract_location_pair(xblock1, xblock2)
        self.assertIn(location_pair, relationship_pairs)

    def assertBlockPairIsNotRelationship(self, xblock1, xblock2, relationships,
                                         relationship_type):
        """
        The opposite of `assertBlockPairIsRelationship`: asserts that a pair
        of xblocks do NOT have a certain kind of relationship.
        """
        relationship_pairs = self._extract_relationship_pairs(
            relationships, relationship_type)
        location_pair = self._extract_location_pair(xblock1, xblock2)
        self.assertNotIn(location_pair, relationship_pairs)

    def test_precedes_relationship(self):
        """
        Tests that two nodes that should have a precedes relationship have it.
        """
        __, relationships = serialize_course(self.course.id)
        self.assertBlockPairIsRelationship(self.video, self.video2,
                                           relationships, "PRECEDES")
        self.assertBlockPairIsNotRelationship(self.video2, self.video,
                                              relationships, "PRECEDES")
        self.assertBlockPairIsNotRelationship(self.vertical, self.video,
                                              relationships, "PRECEDES")
        self.assertBlockPairIsNotRelationship(self.html, self.video,
                                              relationships, "PRECEDES")

    def test_parent_relationship(self):
        """
        Test that two nodes that should have a parent_of relationship have it.
        """
        __, relationships = serialize_course(self.course.id)
        self.assertBlockPairIsRelationship(self.vertical, self.video,
                                           relationships, "PARENT_OF")
        self.assertBlockPairIsRelationship(self.vertical, self.html,
                                           relationships, "PARENT_OF")
        self.assertBlockPairIsRelationship(self.course, self.chapter,
                                           relationships, "PARENT_OF")
        self.assertBlockPairIsNotRelationship(self.course, self.video,
                                              relationships, "PARENT_OF")
        self.assertBlockPairIsNotRelationship(self.video, self.vertical,
                                              relationships, "PARENT_OF")
        self.assertBlockPairIsNotRelationship(self.video, self.html,
                                              relationships, "PARENT_OF")

    def test_nodes_have_indices(self):
        """
        Test that we add index values on nodes
        """
        nodes, relationships = serialize_course(self.course.id)

        # the html node should have 0 index, and the problem should have 1
        html_nodes = [node for node in nodes if node['block_type'] == 'html']
        self.assertEqual(len(html_nodes), 1)
        problem_nodes = [
            node for node in nodes if node['block_type'] == 'problem'
        ]
        self.assertEqual(len(problem_nodes), 1)
        html_node = html_nodes[0]
        problem_node = problem_nodes[0]

        self.assertEqual(html_node['index'], 0)
        self.assertEqual(problem_node['index'], 1)

    @ddt.data(
        (1, 1),
        (object, "<type 'object'>"),
        (1.5, 1.5),
        ("úñîçø∂é", "úñîçø∂é"),
        (b"plain string", b"plain string"),
        (True, True),
        (None, "None"),
        ((1, ), "(1,)"),
        # list of elements should be coerced into a list of the
        # string representations of those elements
        ([object, object], ["<type 'object'>", "<type 'object'>"]))
    @ddt.unpack
    def test_coerce_types(self, original_value, coerced_expected):
        """
        Tests the coerce_types helper
        """
        coerced_value = coerce_types(original_value)
        self.assertEqual(coerced_value, coerced_expected)

    @mock.patch('openedx.core.djangoapps.coursegraph.tasks.NodeSelector')
    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.authenticate_and_create_graph'
    )
    def test_dump_to_neo4j(self, mock_graph_constructor, mock_selector_class):
        """
        Tests the dump_to_neo4j method works against a mock
        py2neo Graph
        """
        mock_graph = MockGraph()
        mock_graph_constructor.return_value = mock_graph
        mock_selector_class.return_value = MockNodeSelector(mock_graph)
        mock_credentials = mock.Mock()

        submitted, skipped = self.mss.dump_courses_to_neo4j(mock_credentials)

        self.assertCourseDump(
            mock_graph,
            number_of_courses=2,
            number_commits=2,
            number_rollbacks=0,
        )

        # 9 nodes + 7 relationships from the first course
        # 2 nodes and no relationships from the second

        self.assertEqual(len(mock_graph.nodes), 11)
        self.assertItemsEqual(submitted, self.course_strings)

    @mock.patch('openedx.core.djangoapps.coursegraph.tasks.NodeSelector')
    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.authenticate_and_create_graph'
    )
    def test_dump_to_neo4j_rollback(self, mock_graph_constructor,
                                    mock_selector_class):
        """
        Tests that the the dump_to_neo4j method handles the case where there's
        an exception trying to write to the neo4j database.
        """
        mock_graph = MockGraph(transaction_errors=True)
        mock_graph_constructor.return_value = mock_graph
        mock_selector_class.return_value = MockNodeSelector(mock_graph)
        mock_credentials = mock.Mock()

        submitted, skipped = self.mss.dump_courses_to_neo4j(mock_credentials)

        self.assertCourseDump(
            mock_graph,
            number_of_courses=0,
            number_commits=0,
            number_rollbacks=2,
        )

        self.assertItemsEqual(submitted, self.course_strings)

    @mock.patch('openedx.core.djangoapps.coursegraph.tasks.NodeSelector')
    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.authenticate_and_create_graph'
    )
    @ddt.data((True, 2), (False, 0))
    @ddt.unpack
    def test_dump_to_neo4j_cache(
        self,
        override_cache,
        expected_number_courses,
        mock_graph_constructor,
        mock_selector_class,
    ):
        """
        Tests the caching mechanism and override to make sure we only publish
        recently updated courses.
        """
        mock_graph = MockGraph()
        mock_graph_constructor.return_value = mock_graph
        mock_selector_class.return_value = MockNodeSelector(mock_graph)
        mock_credentials = mock.Mock()

        # run once to warm the cache
        self.mss.dump_courses_to_neo4j(mock_credentials,
                                       override_cache=override_cache)

        # when run the second time, only dump courses if the cache override
        # is enabled
        submitted, __ = self.mss.dump_courses_to_neo4j(
            mock_credentials, override_cache=override_cache)
        self.assertEqual(len(submitted), expected_number_courses)

    @mock.patch('openedx.core.djangoapps.coursegraph.tasks.NodeSelector')
    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.authenticate_and_create_graph'
    )
    def test_dump_to_neo4j_published(self, mock_graph_constructor,
                                     mock_selector_class):
        """
        Tests that we only dump those courses that have been published after
        the last time the command was been run.
        """
        mock_graph = MockGraph()
        mock_graph_constructor.return_value = mock_graph
        mock_selector_class.return_value = MockNodeSelector(mock_graph)
        mock_credentials = mock.Mock()

        # run once to warm the cache
        submitted, skipped = self.mss.dump_courses_to_neo4j(mock_credentials)
        self.assertEqual(len(submitted), len(self.course_strings))

        # simulate one of the courses being published
        listen_for_course_publish(None, self.course.id)

        # make sure only the published course was dumped
        submitted, __ = self.mss.dump_courses_to_neo4j(mock_credentials)
        self.assertEqual(len(submitted), 1)
        self.assertEqual(submitted[0], six.text_type(self.course.id))

    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.get_course_last_published')
    @mock.patch(
        'openedx.core.djangoapps.coursegraph.tasks.get_command_last_run')
    @ddt.data(
        (six.text_type(datetime(
            2016, 3, 30)), six.text_type(datetime(2016, 3, 31)), True),
        (six.text_type(datetime(
            2016, 3, 31)), six.text_type(datetime(2016, 3, 30)), False),
        (six.text_type(datetime(2016, 3, 31)), None, False),
        (None, six.text_type(datetime(2016, 3, 30)), True),
        (None, None, True),
    )
    @ddt.unpack
    def test_should_dump_course(
        self,
        last_command_run,
        last_course_published,
        should_dump,
        mock_get_command_last_run,
        mock_get_course_last_published,
    ):
        """
        Tests whether a course should be dumped given the last time it was
        dumped and the last time it was published.
        """
        mock_get_command_last_run.return_value = last_command_run
        mock_get_course_last_published.return_value = last_course_published
        mock_course_key = mock.Mock()
        mock_graph = mock.Mock()
        self.assertEqual(
            should_dump_course(mock_course_key, mock_graph),
            should_dump,
        )
Exemplo n.º 37
0
 def to_representation(self, value):
     value = '<br/>'.join(value.splitlines())
     return six.text_type(value)
Exemplo n.º 38
0
 def _make_hash_value(self, user, timestamp):
     return (six.text_type(user.pk) + six.text_type(timestamp) +
             six.text_type(user.profile.email_confirmed))
Exemplo n.º 39
0
    def create(self, request, extra_fields={}, *args, **kwargs):
        """Creates a new diff by parsing an uploaded diff file.

        This will implicitly create the new Review Request draft, which can
        be updated separately and then published.

        This accepts a unified diff file, validates it, and stores it along
        with the draft of a review request. The new diff will have a revision
        of 0.

        A parent diff can be uploaded along with the main diff. A parent diff
        is a diff based on an existing commit in the repository, which will
        be applied before the main diff. The parent diff will not be included
        in the diff viewer. It's useful when developing a change based on a
        branch that is not yet committed. In this case, a parent diff of the
        parent branch would be provided along with the diff of the new commit,
        and only the new commit will be shown.

        It is expected that the client will send the data as part of a
        :mimetype:`multipart/form-data` mimetype. The main diff's name and
        content would be stored in the ``path`` field. If a parent diff is
        provided, its name and content would be stored in the
        ``parent_diff_path`` field.

        An example of this would be::

            -- SoMe BoUnDaRy
            Content-Disposition: form-data; name=path; filename="foo.diff"

            <Unified Diff Content Here>
            -- SoMe BoUnDaRy --

        Extra data can be stored later lookup. See
        :ref:`webapi2.0-extra-data` for more information.
        """
        # Prevent a circular dependency, as ReviewRequestDraftResource
        # needs DraftDiffResource, which needs DiffResource.
        from reviewboard.webapi.resources.review_request_draft import \
            ReviewRequestDraftResource

        try:
            review_request = \
                resources.review_request.get_object(request, *args, **kwargs)
        except ReviewRequest.DoesNotExist:
            return DOES_NOT_EXIST

        if not review_request.is_mutable_by(request.user):
            return self.get_no_access_error(request)

        if review_request.repository is None:
            return INVALID_ATTRIBUTE, {
                'reason':
                'This review request was created as attachments-'
                'only, with no repository.'
            }

        form_data = request.POST.copy()
        form = UploadDiffForm(review_request,
                              form_data,
                              request.FILES,
                              request=request)

        if not form.is_valid():
            return INVALID_FORM_DATA, {
                'fields': self._get_form_errors(form),
            }

        try:
            diffset = form.create(request.FILES['path'],
                                  request.FILES.get('parent_diff_path'))
        except FileNotFoundError as e:
            return REPO_FILE_NOT_FOUND, {
                'file': e.path,
                'revision': six.text_type(e.revision)
            }
        except EmptyDiffError as e:
            return DIFF_EMPTY
        except DiffTooBigError as e:
            return DIFF_TOO_BIG, {
                'reason': six.text_type(e),
                'max_size': e.max_diff_size,
            }
        except Exception as e:
            # This could be very wrong, but at least they'll see the error.
            # We probably want a new error type for this.
            logging.error("Error uploading new diff: %s",
                          e,
                          exc_info=1,
                          request=request)

            return INVALID_FORM_DATA, {'fields': {'path': [six.text_type(e)]}}

        discarded_diffset = None

        try:
            draft = review_request.draft.get()

            if draft.diffset and draft.diffset != diffset:
                discarded_diffset = draft.diffset
        except ReviewRequestDraft.DoesNotExist:
            try:
                draft = ReviewRequestDraftResource.prepare_draft(
                    request, review_request)
            except PermissionDenied:
                return self.get_no_access_error(request)

        draft.diffset = diffset

        # We only want to add default reviewers the first time.  Was bug 318.
        if review_request.diffset_history.diffsets.count() == 0:
            draft.add_default_reviewers()

        draft.save()

        if extra_fields:
            try:
                self.import_extra_data(diffset, diffset.extra_data,
                                       extra_fields)
            except ImportExtraDataError as e:
                return e.error_payload

            diffset.save(update_fields=['extra_data'])

        if discarded_diffset:
            discarded_diffset.delete()

        # E-mail gets sent when the draft is saved.

        return 201, {
            self.item_result_key: diffset,
        }
Exemplo n.º 40
0
 def get_print_name(self):
     if len(self.items) == 1:
         current_owner = self.items[0]
         return current_owner.get_document_filename()
     else:
         return six.text_type(self.caption)
Exemplo n.º 41
0
 def __unicode__(self):
     return "%s (%s)" % (self.revision, six.text_type(self.repository))
Exemplo n.º 42
0
 def writerow(self, row):
     if self.writer is None:
         self.writer = csv.writer(self.f, dialect=self.dialect, **self.kw)
     if not PY3:
         row = [six.text_type(s).encode(self.encoding) for s in row]
     self.writer.writerow(list(row))
Exemplo n.º 43
0
 def __str__(self):
     return six.text_type(self.header)
Exemplo n.º 44
0
 def custom_method(self):
     return six.text_type('{}-{}').format(self.name, self.surname)
Exemplo n.º 45
0
 def __init__(self, message):
     self.message = message
     self.reply_channel = self.message.reply_channel
     self._content_length = 0
     self._post_parse_error = False
     self._read_started = False
     self.resolver_match = None
     # Path info
     self.path = self.message['path']
     self.script_name = self.message.get('root_path', '')
     if self.script_name:
         # TODO: Better is-prefix checking, slash handling?
         self.path_info = self.path[len(self.script_name):]
     else:
         self.path_info = self.path
     # HTTP basics
     self.method = self.message['method'].upper()
     self.META = {
         "REQUEST_METHOD": self.method,
         "QUERY_STRING": self.message.get('query_string', ''),
         "SCRIPT_NAME": self.script_name,
         "PATH_INFO": self.path_info,
         # Old code will need these for a while
         "wsgi.multithread": True,
         "wsgi.multiprocess": True,
     }
     if self.message.get('client', None):
         self.META['REMOTE_ADDR'] = self.message['client'][0]
         self.META['REMOTE_HOST'] = self.META['REMOTE_ADDR']
         self.META['REMOTE_PORT'] = self.message['client'][1]
     if self.message.get('server', None):
         self.META['SERVER_NAME'] = self.message['server'][0]
         self.META['SERVER_PORT'] = six.text_type(self.message['server'][1])
     else:
         self.META['SERVER_NAME'] = "unknown"
         self.META['SERVER_PORT'] = "0"
     # Handle old style-headers for a transition period
     if "headers" in self.message and isinstance(self.message['headers'],
                                                 dict):
         self.message['headers'] = [
             (x.encode("latin1"), y)
             for x, y in self.message['headers'].items()
         ]
     # Headers go into META
     for name, value in self.message.get('headers', []):
         name = name.decode("latin1")
         if name == "content-length":
             corrected_name = "CONTENT_LENGTH"
         elif name == "content-type":
             corrected_name = "CONTENT_TYPE"
         else:
             corrected_name = 'HTTP_%s' % name.upper().replace("-", "_")
         # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
         value = value.decode("latin1")
         if corrected_name in self.META:
             value = self.META[corrected_name] + "," + value
         self.META[corrected_name] = value
     # Pull out request encoding if we find it
     if "CONTENT_TYPE" in self.META:
         self.content_type, self.content_params = cgi.parse_header(
             self.META["CONTENT_TYPE"])
         if 'charset' in self.content_params:
             try:
                 codecs.lookup(self.content_params['charset'])
             except LookupError:
                 pass
             else:
                 self.encoding = self.content_params['charset']
     else:
         self.content_type, self.content_params = "", {}
     # Pull out content length info
     if self.META.get('CONTENT_LENGTH', None):
         try:
             self._content_length = int(self.META['CONTENT_LENGTH'])
         except (ValueError, TypeError):
             pass
     # Body handling
     self._body = message.get("body", b"")
     if message.get("body_channel", None):
         body_handle_start = time.time()
         while True:
             # Get the next chunk from the request body channel
             chunk = None
             while chunk is None:
                 # If they take too long, raise request timeout and the handler
                 # will turn it into a response
                 if time.time(
                 ) - body_handle_start > self.body_receive_timeout:
                     raise RequestTimeout()
                 _, chunk = message.channel_layer.receive_many(
                     [message['body_channel']],
                     block=True,
                 )
             # If chunk contains close, abort.
             if chunk.get("closed", False):
                 raise RequestAborted()
             # Add content to body
             self._body += chunk.get("content", "")
             # Exit loop if this was the last
             if not chunk.get("more_content", False):
                 break
     assert isinstance(self._body, six.binary_type), "Body is not bytes"
     # Add a stream-a-like for the body
     self._stream = BytesIO(self._body)
     # Other bits
     self.resolver_match = None
Exemplo n.º 46
0
 def _make_hash_value(self, user, timestamp):
     return (
         six.text_type(user.pk) + six.text_type(timestamp) +
         six.text_type(user.profile.signup_confirmation)
     )
 def _generate_reference(self):
     obj = hmac.new(key=settings.SECRET_KEY.encode(),
                    msg=six.text_type(self.id).encode())
     return obj.hexdigest().upper()
Exemplo n.º 48
0
 def _make_hash_value(self, user, timestamp):
     return (six.text_type(user.pk) + six.text_type(timestamp)) +  six.text_type(user.is_active)
Exemplo n.º 49
0
 def test_limit_quotes(self):
     with self.assertRaises(ValueError) as cm:
         tag_utils.parse_tags('"adam","brian",chris', 2)
     e = cm.exception
     self.assertEqual(six.text_type(e),
                      "This field can only have 2 arguments")
Exemplo n.º 50
0
 def coerce_result(cls, value):
     return None if value is None else six.text_type(value)
Exemplo n.º 51
0
def show(request, claim_id):
    """View for reviewing a claim.

    :param request: the current HTTP Request object
    :param claim_id: the primary key of the claim to be viewed

    :type request: HttpRequest
    :type claim_id: unicode

    :return:
      the HTTP response object

    :rtype: HttpResponse
    """
    _ = ugettext
    claim = get_object_or_404(models.SampleClaim,
                              pk=utils.convert_id_to_int(claim_id))
    is_reviewer = request.user == claim.reviewer or request.user.is_superuser
    is_requester = request.user == claim.requester
    if not is_reviewer and not is_requester:
        raise permissions.PermissionError(
            request.user,
            _("You are neither the requester nor the reviewer of this claim."))
    if request.method == "POST" and not claim.closed:
        withdraw_form = CloseForm(_("withdraw claim"),
                                  request.POST,
                                  prefix="withdraw") if is_requester else None
        approve_form = CloseForm(_("approve claim"),
                                 request.POST,
                                 prefix="approve") if is_reviewer else None
        all_valid = (withdraw_form is None or withdraw_form.is_valid()) and (
            approve_form is None or approve_form.is_valid())
        referencially_valid = is_referentially_valid(withdraw_form,
                                                     approve_form)
        if all_valid and referencially_valid:
            approved = approve_form and approve_form.cleaned_data["close"]
            closed = approved or (withdraw_form
                                  and withdraw_form.cleaned_data["close"])
            response = None
            if approved:
                sample_list = list(claim.samples.all())
                for sample in sample_list:
                    sample.currently_responsible_person = claim.requester
                    sample.save()
                sample_enumeration = "    " + ",\n    ".join(
                    six.text_type(sample) for sample in sample_list)
                _ = lambda x: x
                send_email(
                    _("Sample request approved"),
                    _("""Hello {requester},

your sample claim was approved.  You are now the “currently
responsible person” of the following samples:

{samples}

JuliaBase.
"""), claim.requester, {
                        "requester": get_really_full_name(claim.requester),
                        "samples": sample_enumeration
                    })
                _ = ugettext
                response = \
                    utils.successful_response(request,
                                              _("Sample claim {id_} was successfully approved.").format(id_=claim.pk))
            if closed:
                claim.closed = True
                claim.save()
                response = response or \
                    utils.successful_response(request,
                                              _("Sample claim {id_} was successfully withdrawn.").format(id_=claim.pk))
            return response
    else:
        withdraw_form = CloseForm(_("withdraw claim"),
                                  prefix="withdraw") if is_requester else None
        approve_form = CloseForm(_("approve claim"),
                                 prefix="approve") if is_reviewer else None
    return render(
        request, "samples/show_claim.html", {
            "title": _("Claim #{number}").format(number=claim_id),
            "claim": claim,
            "is_reviewer": is_reviewer,
            "is_requester": is_requester,
            "withdraw": withdraw_form,
            "approve": approve_form
        })
Exemplo n.º 52
0
 def __init__(self, translations):
     if not isinstance(translations, dict):
         translations = {FALLBACK_LANG: text_type(translations)}
     self._src = translations
Exemplo n.º 53
0
def make_checksum(parsed, unique_values=None):
    unique_values = unique_values or []
    seeds = [parsed] + [six.text_type(v) for v in unique_values]

    return sha256('+'.join(seeds).encode("utf-8")).hexdigest()
Exemplo n.º 54
0
 def test_limit(self):
     with self.assertRaises(ValueError) as cm:
         tag_utils.parse_tags("adam,brian,chris", 1)
     e = cm.exception
     self.assertEqual(six.text_type(e),
                      "This field can only have 1 argument")
Exemplo n.º 55
0
 def __str__(self):
     return six.text_type('{} ({})'.format(self.subject, self.language))
Exemplo n.º 56
0
 class Meta:
     model = Person
     fields = (six.text_type('first_name'), )
Exemplo n.º 57
0
def assignment_only_unlimited_args(*args):
    """Expected assignment_only_unlimited_args __doc__"""
    return "assignment_only_unlimited_args - Expected result: %s" % ', '.join(
        six.text_type(arg) for arg in args)
Exemplo n.º 58
0
 def update_id_mapping(self, data):
     user_id = text_type(data["id"])
     screen_name = data["screen_name"]
     self.screen_name_to_user_id[screen_name.lower()] = user_id
     self.user_id_to_screen_name[user_id] = screen_name
     self.user_id_to_photo_url[user_id] = data["profile_image_url_https"]
Exemplo n.º 59
0
def simple_only_unlimited_args(*args):
    """Expected simple_only_unlimited_args __doc__"""
    return "simple_only_unlimited_args - Expected result: %s" % ', '.join(
        six.text_type(arg) for arg in args)
Exemplo n.º 60
0
def simple_unlimited_args(one, two='hi', *args):
    """Expected simple_unlimited_args __doc__"""
    return "simple_unlimited_args - Expected result: %s" % (', '.join(
        six.text_type(arg) for arg in [one, two] + list(args)))