Best Python code snippet using Kiwi_python
cms_plugins.py
Source:cms_plugins.py  
...36        })37        return context38    def icon_src(self, instance):39        return static_url("img/table.png")40    def response_change(self, request, obj):41        42        response = super(AssociatedcompPlugin, self).response_change(request, obj)43        44        if 'csv_upload' in request.FILES.keys():45            self.object_successfully_changed = False46        return response47class SequencesPlugin(CMSPluginBase):48    model = Sequences49    form = SequencesForm50    render_template = "cms/plugins/sequences.html"51    text_enabled = True52    fieldsets = (53        (None, {54            'fields': ('name',)55        }),56        (None, {57            'fields':('sequence_prefix',)58        }),59        (_('Headers'), {60            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)61        }),62        (None, {63            'fields': ('table_data', 'csv_upload')64        })65    )66    def render(self, context, instance, placeholder):67        try:68            data = simplejson.loads(instance.table_data)69        except:70            data = "error"71        context.update({72            'name': instance.name,73            'data': data,74            'instance':instance,75        })76        return context77    def icon_src(self, instance):78        return static_url("img/table.png")79    def response_change(self, request, obj):80        81        response = super(SequencesPlugin, self).response_change(request, obj)82        83        if 'csv_upload' in request.FILES.keys():84            self.object_successfully_changed = False85        return response86class NomenclaturePlugin(CMSPluginBase):87    model = Nomenclature88    form = NomenclatureForm89    render_template = "cms/plugins/nomenclature.html"90    text_enabled = True91    fieldsets = (92        (None, {93            'fields': ('name',)94        }),95        (_('Headers'), {96            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)97        }),98        (None, {99            'fields': ('table_data', 'csv_upload')100        })101    )102    def render(self, context, instance, placeholder):103        try:104            data = simplejson.loads(instance.table_data)105        except:106            data = "error"107        context.update({108            'name': instance.name,109            'data': data,110            'instance':instance,111        })112        return context113    def icon_src(self, instance):114        return static_url("img/table.png")115    def response_change(self, request, obj):116        117        response = super(NomenclaturePlugin, self).response_change(request, obj)118        119        if 'csv_upload' in request.FILES.keys():120            self.object_successfully_changed = False121        return response122class AnnotationPlugin(CMSPluginBase):123    model = Annotation124    form = AnnotationForm125    render_template = "cms/plugins/annotation.html"126    text_enabled = True127    128    fieldsets = (129        (None, {130            'fields': ('name',)131        }),132        (_('Headers'), {133            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)134        }),135        (None, {136            'fields': ('table_data', 'csv_upload')137        })138    )139    def render(self, context, instance, placeholder):140        try:141            142            data = instance.table_data143            data = simplejson.loads(data)144        except:145            data = "error"146            147            148        context.update({149            'name': instance.name,150            'data': simplejson.loads(instance.table_data),151            'instance':instance,152        })153        return context154    def icon_src(self, instance):155        return static_url("img/table.png")156    def response_change(self, request, obj):157        158        response = super(AnnotationPlugin, self).response_change(request, obj)159        160        if 'csv_upload' in request.FILES.keys():161            self.object_successfully_changed = False162        return response163class ExpressionPlugin(CMSPluginBase):164    model = Expression165    form = ExpressionForm166    render_template = "cms/plugins/expression.html"167    text_enabled = True168    fieldsets = (169        (None, {170            'fields': ('name',)171        }),172        (_('Headers'), {173            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)174        }),175        (None, {176            'fields': ('table_data', 'csv_upload')177        })178    )179    def render(self, context, instance, placeholder):180        try:181            #$ print instance.table_data182            #instance.table_data = instance.table_data.replace("is","are")183            data = simplejson.loads(instance.table_data)184            #if type(data) == list:185            #    print data186            #    data = [[x.replace("is","are") for x in i] for i in data]187        except:188            data = "error"189        context.update({190            'name': instance.name,191            'data': data,192            'instance':instance,193            'json_data': instance.table_data,194        })195        return context196    def icon_src(self, instance):197        return static_url("img/table.png")198    def response_change(self, request, obj):199         200        response = super(ExpressionPlugin, self).response_change(request, obj)201        if 'csv_upload' in request.FILES.keys():202            self.object_successfully_changed = False203        return response204        205        206class SpeciesPlugin(CMSPluginBase):207    model = Species208    form = SpeciesForm209    render_template = "cms/plugins/species.html"210    text_enabled = True211    fieldsets = (212        (None, {213            'fields': ('name',)214        }),215        (_('Headers'), {216            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)217        }),218        (None, {219            'fields': ('table_data', 'csv_upload')220        })221    )222    223    224    def render(self, context, instance, placeholder):225        try:226            227            data = instance.table_data228            data = simplejson.loads(data)229        except:230            data = "error"231            232            233        context.update({234            'name': instance.name,235            'data': simplejson.loads(instance.table_data),236            'instance':instance,237        })238        return context239    def icon_src(self, instance):240        return static_url("img/table.png")241    def response_change(self, request, obj):242         243        response = super(SpeciesPlugin, self).response_change(request, obj)244        if 'csv_upload' in request.FILES.keys():245            self.object_successfully_changed = False246        return response247        248        249        250class LiteraturePlugin(CMSPluginBase):251    model = Literature252    form = LiteratureForm253    render_template = "cms/plugins/literature.html"254    text_enabled = True255    fieldsets = (256        (None, {257            'fields': ('name',)258        }),259        (_('Headers'), {260            'fields': (('headers_top', 'headers_left', 'headers_bottom'),)261        }),262        (None, {263            'fields': ('table_data', 'csv_upload')264        })265    )266    def render(self, context, instance, placeholder):267        try:268            data = instance.table_data269            data = simplejson.loads(instance.data)270        except:271            data = "error"272        context.update({273            'name': instance.name,274            'data': simplejson.loads(instance.table_data),275            'instance':instance,276        })277        return context278    def icon_src(self, instance):279        return static_url("img/table.png")280    def response_change(self, request, obj):281         282        response = super(LiteraturePlugin, self).response_change(request, obj)283        if 'csv_upload' in request.FILES.keys():284            self.object_successfully_changed = False285        return response286plugin_pool.register_plugin(AnnotationPlugin)287plugin_pool.register_plugin(ExpressionPlugin)288plugin_pool.register_plugin(SpeciesPlugin)289plugin_pool.register_plugin(LiteraturePlugin)290plugin_pool.register_plugin(NomenclaturePlugin)291plugin_pool.register_plugin(SequencesPlugin)292plugin_pool.register_plugin(AssociatedcompPlugin)293        #data_2 = obj.table_data294        #print type(data_2)295        #data_2 = data_2.replace("ky","kyness")296        #obj.table_data = data_2...test_user_edit.py
Source:test_user_edit.py  
1import time2import allure3import pytest4from lib.base_case import BaseCase5from lib.assertions import Assertions6from lib.my_requests import MyRequests7@allure.epic("User edit cases")8class TestUserEdit(BaseCase):9    @pytest.mark.smoke10    @allure.story("crud")11    @allure.title("Edit created user")12    @allure.description("This test ensure user can edit its own details")13    def test_edit_just_created_user(self):14        register_data = self.prepare_registration_data()15        response_registration = MyRequests.post("/user", data=register_data)16        Assertions.assert_code_status(response_registration, 200)17        Assertions.assert_json_has_key(response_registration, "id")18        email = register_data['email']19        password = register_data['password']20        user_id = self.get_json_value(response_registration, "id")21        login_data = {22            "email": email,23            "password": password24        }25        response_auth = MyRequests.post("/user/login", data=login_data)26        auth_sid = self.get_cookie(response_auth, "auth_sid")27        token = self.get_header(response_auth, "x-csrf-token")28        new_name = "Changed Name"29        response_change = MyRequests.put(f"/user/{user_id}",30                                         headers={"x-csrf-token": token},31                                         cookies={"auth_sid": auth_sid},32                                         data={"firstName": new_name})33        Assertions.assert_code_status(response_change, 200)34        response_check_name = MyRequests.get(f"/user/{user_id}",35                                             headers={"x-csrf-token": token},36                                             cookies={"auth_sid": auth_sid})37        Assertions.assert_json_value_by_name(response_check_name,38                                             "firstName",39                                             new_name,40                                             "Wrong firstName after edit")41    # python -m pytest -s .\tests\test_user_edit.py -k test_edit_created_user_unauth42    @allure.title("Unauth user cannot edit {field}")43    @allure.description("This test ensure unauthorized user can't edit it's own details")44    @pytest.mark.parametrize('field', ["username", "firstName", "lastName", "email", "password"])45    def test_edit_created_user_unauth(self, field):46        user_data = self.create_user_ensure_created()47        new_value = 'new' + user_data[field]48        response_change = MyRequests.put(f"/user/{user_data['user_id']}", data={field: new_value})49        Assertions.assert_code_status(response_change, 400)50        assert response_change.text == f"Auth token not supplied", \51            f'Unexpected response text {response_change.text}'52    # python -m pytest -s .\tests\test_user_edit.py -k test_edit_other_user_auth53    @allure.title("Unauth user cannot edit {field} of other user")54    @allure.description("This test ensure authorized user can edit other user details, but details are not changed")55    @pytest.mark.parametrize('field', ["username", "firstName", "lastName", "email", "password"])56    def test_edit_other_user_auth(self, field):57        user_auth = self.create_user_ensure_created()58        user_auth = self.get_auth_data(user_auth)59        time.sleep(2)60        user_to_edit = self.create_user_ensure_created()61        user_to_edit = self.get_auth_data(user_to_edit)62        new_value = 'new' + user_to_edit[field]63        response_change = MyRequests.put(f"/user/{user_to_edit['user_id']}",64                                         headers={"x-csrf-token": user_auth["token"]},65                                         cookies={"auth_sid": user_auth["auth_sid"]},66                                         data={field: new_value})67        Assertions.assert_code_status(response_change, 200)68        response_get = MyRequests.get(f"/user/{user_to_edit['user_id']}",69                                      headers={"x-csrf-token": user_to_edit["token"]},70                                      cookies={"auth_sid": user_to_edit["auth_sid"]})71        if field == 'password':72            response_try_auth = MyRequests.post("/user/login",73                                                data={"email": user_to_edit["email"],74                                                      "password": new_value})75            Assertions.assert_code_status(response_try_auth, 400)76            assert response_try_auth.text == 'Invalid username/password supplied', \77                f'Was able to login with changed password {new_value}'78        else:79            Assertions.assert_json_value_by_name(80                response_get,81                field,82                user_to_edit[field],83                f"Value of the '{field}' was changed to '{new_value}' incorrectly. "84                f"Value should not be changed by other user")85    # python -m pytest -s .\tests\test_user_edit.py -k test_edit_auth_user_email_format86    @allure.title("User can't remove @ from email")87    @allure.description("This test ensure authorized user can't edit it's own email to incorrect format")88    def test_edit_auth_user_email_format(self):89        user = self.create_user_ensure_created()90        user = self.get_auth_data(user)91        new_value = 'emailwithoutat.com'92        response_change = MyRequests.put(f"/user/{user['user_id']}",93                                         headers={"x-csrf-token": user["token"]},94                                         cookies={"auth_sid": user["auth_sid"]},95                                         data={"email": new_value})96        Assertions.assert_code_status(response_change, 400)97        assert response_change.text == 'Invalid email format', \98            f'Was able to change email to incorrect format {new_value}' \99            f' or got other error {response_change.text}'100    # python -m pytest -s .\tests\test_user_edit.py -k test_edit_auth_user_firstname_short101    @allure.title("User can't put too short firstName")102    @allure.description("This test ensure authorized user can't edit it's own firstName to incorrect format")103    def test_edit_auth_user_firstname_short(self):104        user = self.create_user_ensure_created()105        user = self.get_auth_data(user)106        new_value = 'b'107        response_change = MyRequests.put(f"/user/{user['user_id']}",108                                         headers={"x-csrf-token": user["token"]},109                                         cookies={"auth_sid": user["auth_sid"]},110                                         data={"firstName": new_value})111        Assertions.assert_code_status(response_change, 400)112        assert response_change.text == '{"error":"Too short value for field firstName"}', \...admin.py
Source:admin.py  
...4from django.http import HttpResponseRedirect5class MyModelAdmin(ImageCroppingMixin, admin.ModelAdmin):6    change_form_template = "../templates/journal/admin_edit.html"7    search_fields = ("last_name", "first_name", "middle_name", "squad__code")8    def response_change(self, request, obj):9        if "_back" in request.POST:10            return HttpResponseRedirect("/journal/students/{}".format(obj.id))11        return super().response_change(request, obj)12class PersonalInfoModelAdmin(admin.ModelAdmin):13    change_form_template = "../templates/journal/admin_edit.html"14    search_fields = (15        "student__last_name",16        "student__first_name",17        "student__middle_name",18        "student__squad__code",19    )20    def response_change(self, request, obj):21        if "_back" in request.POST:22            return HttpResponseRedirect("/journal/students/{}".format(obj.student.id))23        return super().response_change(request, obj)24class AttendanceModelAdmin(admin.ModelAdmin):25    change_form_template = "../templates/journal/admin_edit.html"26    def response_change(self, request, obj):27        if "_back" in request.POST:28            return HttpResponseRedirect("/journal/attendance/{}".format(obj.id))29        return super().response_change(request, obj)30# Register your models here.31admin.site.register(Subject)32admin.site.register(Student, MyModelAdmin)33admin.site.register(Squad)34admin.site.register(TimeTable)35admin.site.register(PersonalInfo, PersonalInfoModelAdmin)36admin.site.register(Penalty)37admin.site.register(Exam)38admin.site.register(Attendance, AttendanceModelAdmin)39admin.site.register(Lesson)40admin.site.register(Event)41admin.site.register(EventParticipant)...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
