How to use gen_ignore method in hypothesis

Best Python code snippet using hypothesis

merge.py

Source: merge.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from datetime import datetime3from django.utils.encoding import force_unicode4from adminactions import api5from django.contrib import messages6from django.contrib.admin import helpers7from django import forms8from django.forms import TextInput, HiddenInput9from django.db import models10from django.forms.formsets import formset_factory11from django.forms.models import modelform_factory, model_to_dict12from django.shortcuts import render_to_response13from django.template import RequestContext14from django.utils.safestring import mark_safe15from django.http import HttpResponseRedirect16from django.utils.translation import gettext as _17from adminactions.forms import GenericActionForm18from adminactions.models import get_permission_codename19from adminactions.utils import clone_instance, model_supports_transactions20import adminactions.compat as transaction21class MergeForm(GenericActionForm):22 DEP_MOVE = 123 DEP_DELETE = 224 GEN_IGNORE = 125 GEN_RELATED = 226 GEN_DEEP = 327 dependencies = forms.ChoiceField(label=_('Dependencies'),28 choices=((DEP_MOVE, _("Move")), (DEP_DELETE, _("Delete"))))29 # generic = forms.ChoiceField(label=_('Search GenericForeignKeys'),30 # help_text=_("Search for generic relation"),31 # choices=((GEN_IGNORE, _("No")),32 # (GEN_RELATED, _("Only Related (look for Managers)")),33 # (GEN_DEEP, _("Analyze Mode (very slow)"))))34 master_pk = forms.CharField(widget=HiddenInput)35 other_pk = forms.CharField(widget=HiddenInput)36 field_names = forms.CharField(required=False, widget=HiddenInput)37 def action_fields(self):38 for fieldname in ['dependencies', 'master_pk', 'other_pk', 'field_names']:39 bf = self[fieldname]40 yield HiddenInput().render(fieldname, bf.value())41 def clean_dependencies(self):42 return int(self.cleaned_data['dependencies'])43 def clean_field_names(self):44 return self.cleaned_data['field_names'].split(',')45 def full_clean(self):46 super(MergeForm, self).full_clean()47 def clean(self):48 return super(MergeForm, self).clean()49 def is_valid(self):50 return super(MergeForm, self).is_valid()51 class Media:52 js = ['adminactions/​js/​merge.min.js']53 css = {'all': ['adminactions/​css/​adminactions.min.css']}54def merge(modeladmin, request, queryset):55 """56 Merge two model instances. Move all foreign keys.57 """58 opts = modeladmin.model._meta59 perm = "{0}.{1}".format(opts.app_label.lower(), get_permission_codename('adminactions_merge', opts))60 if not request.user.has_perm(perm):61 messages.error(request, _('Sorry you do not have rights to execute this action (%s)' % perm))62 return63 def raw_widget(field, **kwargs):64 """ force all fields as not required"""65 kwargs['widget'] = TextInput({'class': 'raw-value'})66 return field.formfield(**kwargs)67 merge_form = getattr(modeladmin, 'merge_form', MergeForm)68 MForm = modelform_factory(modeladmin.model,69 form=merge_form,70 exclude=('pk', ),71 formfield_callback=raw_widget)72 OForm = modelform_factory(modeladmin.model,73 exclude=('pk', ),74 formfield_callback=raw_widget)75 tpl = 'adminactions/​merge.html'76 # transaction_supported = model_supports_transactions(modeladmin.model)77 ctx = {78 '_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),79 'transaction_supported': 'Un',80 'select_across': request.POST.get('select_across') == '1',81 'action': request.POST.get('action'),82 'fields': [f for f in queryset.model._meta.fields if not f.primary_key and f.editable],83 'app_label': queryset.model._meta.app_label,84 'result': '',85 'opts': queryset.model._meta}86 if 'preview' in request.POST:87 master = queryset.get(pk=request.POST.get('master_pk'))88 original = clone_instance(master)89 other = queryset.get(pk=request.POST.get('other_pk'))90 formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])91 with transaction.nocommit():92 form = MForm(request.POST, instance=master)93 other.delete()94 form_is_valid = form.is_valid()95 if form_is_valid:96 ctx.update({'original': original})97 tpl = 'adminactions/​merge_preview.html'98 else:99 master = queryset.get(pk=request.POST.get('master_pk'))100 other = queryset.get(pk=request.POST.get('other_pk'))101 elif 'apply' in request.POST:102 master = queryset.get(pk=request.POST.get('master_pk'))103 other = queryset.get(pk=request.POST.get('other_pk'))104 formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])105 with transaction.nocommit():106 form = MForm(request.POST, instance=master)107 stored_pk = other.pk108 other.delete()109 ok = form.is_valid()110 other.pk = stored_pk111 if ok:112 if form.cleaned_data['dependencies'] == MergeForm.DEP_MOVE:113 related = api.ALL_FIELDS114 else:115 related = None116 fields = form.cleaned_data['field_names']117 api.merge(master, other, fields=fields, commit=True, related=related)118 return HttpResponseRedirect(request.path)119 else:120 messages.error(request, form.errors)121 else:122 try:123 master, other = queryset.all()124 # django 1.4 need to remove the trailing milliseconds125 for field in master._meta.fields:126 if isinstance(field, models.DateTimeField):127 for target in (master, other):128 raw_value = getattr(target, field.name)129 fixed_value = datetime(raw_value.year, raw_value.month, raw_value.day,130 raw_value.hour, raw_value.minute, raw_value.second)131 setattr(target, field.name, fixed_value)132 except ValueError:133 messages.error(request, _('Please select exactly 2 records'))134 return135 initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),136 'select_across': 0,137 'generic': MergeForm.GEN_IGNORE,138 'dependencies': MergeForm.DEP_MOVE,139 'action': 'merge',140 'master_pk': master.pk,141 'other_pk': other.pk}142 formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])143 form = MForm(initial=initial, instance=master)144 adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)145 media = modeladmin.media + adminForm.media146 ctx.update({'adminform': adminForm,147 'formset': formset,148 'media': mark_safe(media),149 'title': u"Merge %s" % force_unicode(modeladmin.opts.verbose_name_plural),150 'master': master,151 'other': other})152 return render_to_response(tpl, RequestContext(request, ctx))...

Full Screen

Full Screen

codegen.py

Source: codegen.py Github

copy

Full Screen

...26 def gen_footer(self) -> List[str]:27 return [28 '#endif /​* {} */​'.format(self.mark),29 ]30 def gen_ignore(self) -> List[str]:31 return [32 '#define _VARDEF_IGNORE(...)'33 ]34 def gen_pack(self, num_group: int, group_size: int) -> List[str]:35 exprs = [] # type: List[str]36 # common37 vardef = 'VARDEF{}'.format(group_size)38 prefix = '_' + vardef + '_'39 # generate SELECT40 elems = [] # type: List[str]41 for i in range(num_group + 1):42 for j in range(group_size):43 elems.append('{}{}'.format(Generator_VARDEF.CHARSET[j], i))44 exprs.append(45 '#define {}SELECT({}, N, ...) N'.format(46 prefix, ', '.join(elems)47 )48 )49 # generate GROUP_X50 arg_group = ', '.join([51 Generator_VARDEF.CHARSET[j] for j in range(group_size)52 ])53 exprs.append(54 '#define {}GROUP0(Func, None, ...) None'.format(55 prefix56 )57 )58 for i in range(1, num_group + 1, 1):59 exprs.append(' '.join([60 '#define',61 '{}GROUP{}(Func, None, {}, ...)'.format(prefix, i, arg_group),62 'Func({})'.format(arg_group),63 '{}GROUP{}(Func, None, ##__VA_ARGS__)'.format(prefix, i - 1),64 ]))65 # generate VARDEF66 exprs.append(' '.join([67 '#define',68 '{}(Func, None, ...)'.format(vardef),69 '{}SELECT({}##__VA_ARGS__, {})(Func, None, ##__VA_ARGS__)'.format(70 prefix, ', ' * group_size, ', '.join([71 '{}GROUP{}'.format(prefix, i) +72 ', _VARDEF_IGNORE' * (group_size - 1)73 for i in range(num_group, -1, -1)74 ])75 )76 ]))77 return exprs78 def gen(self) -> str:79 stmts = self.gen_header() + self.gen_ignore()80 for i in range(1, self.max_group_size + 1, 1):81 stmts += self.gen_pack(self.num_group, i)82 stmts += self.gen_footer()83 return '\n'.join(stmts)84if __name__ == '__main__':85 g = Generator_VARDEF(num_group=8, max_group_size=6)...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

Joomla Testing Guide: How To Test Joomla Websites

Before we discuss the Joomla testing, let us understand the fundamentals of Joomla and how this content management system allows you to create and maintain web-based applications or websites without having to write and implement complex coding requirements.

Now Log Bugs Using LambdaTest and DevRev

In today’s world, an organization’s most valuable resource is its customers. However, acquiring new customers in an increasingly competitive marketplace can be challenging while maintaining a strong bond with existing clients. Implementing a customer relationship management (CRM) system will allow your organization to keep track of important customer information. This will enable you to market your services and products to these customers better.

Why Agile Teams Have to Understand How to Analyze and Make adjustments

How do we acquire knowledge? This is one of the seemingly basic but critical questions you and your team members must ask and consider. We are experts; therefore, we understand why we study and what we should learn. However, many of us do not give enough thought to how we learn.

27 Best Website Testing Tools In 2022

Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.

11 Best Mobile Automation Testing Tools In 2022

Mobile application development is on the rise like never before, and it proportionally invites the need to perform thorough testing with the right mobile testing strategies. The strategies majorly involve the usage of various mobile automation testing tools. Mobile testing tools help businesses automate their application testing and cut down the extra cost, time, and chances of human error.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful