Best Python code snippet using autotest_python
clazz.py
Source:clazz.py  
1from flask import Blueprint, render_template, flash, redirect, url_for, request, current_app, session, jsonify2from flask_login import login_required, current_user3from com.models import BizAssetClass, RelAssetClass4from com.plugins import db5from com.decorators import log_record6from com.forms.biz.master.clazz import ClazzSearchForm, ClazzForm7import uuid, time8from datetime import datetime9bp_clazz = Blueprint('clazz', __name__)10@bp_clazz.route('/index', methods=['GET', 'POST'])11@login_required12@log_record('æ¥çèµäº§å类信æ¯')13def index():14    form = ClazzSearchForm()15    if request.method == 'GET':16        page = request.args.get('page', 1, type=int)17        try:18            code = session['clazz_view_search_code'] if session['clazz_view_search_code'] else ''  # åå
¸ä»£ç 19            name = session['clazz_view_search_name'] if session['clazz_view_search_name'] else ''  # åå
¸åç§°20        except KeyError:21            code = ''22            name = ''23        form.code.data = code24        form.name.data = name25    if request.method == 'POST':26        page = 127        code = form.code.data28        name = form.name.data29        session['clazz_view_search_code'] = code30        session['clazz_view_search_name'] = name31    per_page = current_app.config['ITEM_COUNT_PER_PAGE']32    pagination = BizAssetClass.query.filter(BizAssetClass.bg_id == current_user.company_id).filter(BizAssetClass.code.like('%' + code.upper() + '%'), BizAssetClass.name.like('%' + name + '%')).order_by(BizAssetClass.code).paginate(page, per_page)33    clazzes = pagination.items34    return render_template('biz/master/clazz/index.html', form=form, clazzes=clazzes, pagination=pagination)35@bp_clazz.route('/add', methods=['GET', 'POST'])36@login_required37@log_record('æ°å¢èµäº§å类信æ¯')38def add():39    form = ClazzForm()40    form.parent.choices = get_parents()41    if request.method == 'GET':42        form.has_parent.data = True43    if form.validate_on_submit():44        if not form.has_parent.data or not form.parent.data:45            grade = 146        else:47            parent = BizAssetClass.query.get(form.parent.data)48            grade = parent.grade + 149        clazz = BizAssetClass(50            id=uuid.uuid4().hex,51            code=form.code.data.upper(),52            name=form.name.data,53            unit=form.unit.data,54            grade=grade,55            bg_id=current_user.company_id,56            create_id=current_user.id57        )58        db.session.add(clazz)59        db.session.commit()60        # 设置ä¸çº§å¤§ç±»61        if grade != 1:62            clazz.set_parent_class(parent)63        flash('èµäº§ç±»å«æ·»å æåï¼')64        return redirect(url_for('.index'))65    return render_template('biz/master/clazz/add.html', form=form)66@bp_clazz.route('/edit/<id>', methods=['GET', 'POST'])67@login_required68@log_record('ä¿®æ¹èµäº§ç±»å«ä¿¡æ¯')69def edit(id):70    form = ClazzForm()71    clazz = BizAssetClass.query.get_or_404(id)72    form.parent.choices = get_parents(clazz)73    if request.method == 'GET':74        form.id.data = id75        form.code.data = clazz.code76        form.name.data = clazz.name77        form.has_parent.data = True if clazz.get_parent_class else False78        form.parent.data = clazz.get_parent_class.id if clazz.get_parent_class else ''79        form.unit.data = clazz.unit80    if form.validate_on_submit():81        if not form.has_parent.data or not form.parent.data:82            grade = 183        else:84            parent = BizAssetClass.query.get(form.parent.data)85            grade = parent.grade + 186        clazz.code = form.code.data.upper()87        clazz.name = form.name.data88        clazz.grade = grade89        clazz.unit = form.unit.data90        clazz.update_id = current_user.id91        clazz.updatetime_utc = datetime.utcfromtimestamp(time.time())92        clazz.updatetime_loc = datetime.fromtimestamp(time.time())93        db.session.commit()94        # 妿æ¯1ççº§å³æ ¹ç±»å«ï¼åå é¤å
³èå
³ç³»ï¼å¦åéæ°è®¾å®æ°ä¸çº§ç±»å«95        if grade == 1:96            parent_class = RelAssetClass.query.filter_by(child_class_id=id).first()97            db.session.delete(parent_class)98            db.session.commit()99        else:100            clazz.set_parent_class(parent)101        flash('èµäº§ç±»å«ä¿®æ¹æåï¼')102        return redirect(url_for('.index'))103    return render_template('biz/master/clazz/edit.html', form=form)104@bp_clazz.route('/grade/<id>', methods=['POST'])105@login_required106@log_record('è·åç±»å«ç级信æ¯')107def grade(id):108    clazz = BizAssetClass.query.get_or_404(id)109    return jsonify(grade=clazz.grade)110def get_parents(clazz=None):111    '''112    è·å1/2级类å«ä¾éæ©113    :param clazz_id: 为空表示æ°å¢ï¼å¦å表示ç¼è¾114    :return:115    '''116    if clazz:117        # è·åæ¬ç±»å«IDååç±»å«ID118        self_and_child_ids = [clazz.id]119        get_self_and_child_ids(clazz, self_and_child_ids)120        # å餿èªèº«ååç±»å«ID121        return [(clazz.id, (clazz.get_parent_class.name+' / ' if clazz.get_parent_class else '')+clazz.name) for clazz in BizAssetClass.query.filter(BizAssetClass.grade.in_([1, 2])).filter(~BizAssetClass.id.in_(self_and_child_ids)).order_by(BizAssetClass.grade, BizAssetClass.createtime_loc).all()]122    else:123        return [(clazz.id, (clazz.get_parent_class.name + ' / ' if clazz.get_parent_class else '') + clazz.name) for clazz in BizAssetClass.query.filter(BizAssetClass.grade.in_([1, 2])).order_by(BizAssetClass.grade, BizAssetClass.createtime_loc).all()]124def get_self_and_child_ids(parent, children):125    '''126    éå½è·åç±»å«ååç±»å«ID127    :param clazz:128    :param self_and_children_ids:129    :return:130    '''131    children_clazz = parent.get_child_class132    if children_clazz:133        for child_clazz in children_clazz:134            children.append(child_clazz.child_class_id)135            get_self_and_child_ids(BizAssetClass.query.get(child_clazz.child_class_id), children)136    else:137        return children138@bp_clazz.route('/get_class2_options', methods=['GET', 'POST'])139@login_required140@log_record('è·åäºçº§åç±»ä¸æé项')141def get_class2_options():142    class2 = BizAssetClass.query.filter_by(grade=2).order_by(BizAssetClass.name).all()143    options = [(clazz.id, clazz.name) for clazz in class2]144    return jsonify(options=options)145@bp_clazz.route('/get_class3_options/<class2_id>', methods=['POST'])146@login_required147@log_record('è·åä¸çº§åç±»ä¸æé项')148def get_class3_options(class2_id):149    class2 = BizAssetClass.query.get(class2_id)150    options = [(rel.child_class_id, rel.child_class.name) for rel in class2.get_child_class]151    return jsonify(options=options)152@bp_clazz.route('/get_class3_unit/<class3_id>', methods=['POST'])153@login_required154@log_record('è·åä¸çº§åç±»åä½')155def get_class3_unit(class3_id):156    class3 = BizAssetClass.query.get(class3_id)...test_anonymizer.py
Source:test_anonymizer.py  
...50    anon_name_2 = anonymizer2._anonymize_string(test_name)51    assert anon_name_1 == anon_name_252    assert len(anon_name_1) == 3253    assert len(anon_name_2) == 3254def test_anonymizer_get_parent_class():55    """56    What does this test and why?57    The method Anonymizer.get_parent_class() should return the name of the parent class if it is or is a subclass of one of the classes_to_check. If not, it should return None. It should do so regardless of the parameter used to pass in the object definition (object_, object_class, object_config). It should also return the first matching class in classes_to_check, even if a later class also matches.58    """59    anonymizer = Anonymizer()60    # classes_to_check in order of inheritance hierarchy61    classes_to_check = [TestClass, BaseTestClass]62    assert (63        anonymizer.get_parent_class(64            classes_to_check=classes_to_check, object_class=MyCustomTestClass65        )66        == "TestClass"67    )68    assert (69        anonymizer.get_parent_class(70            classes_to_check=classes_to_check, object_class=SomeOtherClass71        )72        is None73    )74    classes_to_check = [BaseTestClass]75    assert (76        anonymizer.get_parent_class(77            classes_to_check=classes_to_check, object_class=TestClass78        )79        == "BaseTestClass"80    )81    # classes_to_check in order of inheritance hierarchy82    my_custom_test_class = MyCustomTestClass()83    test_class = TestClass()84    some_other_class = SomeOtherClass()85    classes_to_check = [TestClass, BaseTestClass]86    assert (87        anonymizer.get_parent_class(88            classes_to_check=classes_to_check, object_=my_custom_test_class89        )90        == "TestClass"91    )92    assert (93        anonymizer.get_parent_class(94            classes_to_check=classes_to_check, object_=some_other_class95        )96        is None97    )98    classes_to_check = [BaseTestClass]99    assert (100        anonymizer.get_parent_class(101            classes_to_check=classes_to_check, object_=test_class102        )103        == "BaseTestClass"104    )105    # classes_to_check in order of inheritance hierarchy106    my_custom_test_class_config = {107        "class_name": "MyCustomTestClass",108        "module_name": "tests.core.usage_statistics.test_anonymizer",109    }110    test_class_config = {111        "class_name": "TestClass",112        "module_name": "tests.core.usage_statistics.test_anonymizer",113    }114    some_other_class_config = {115        "class_name": "SomeOtherClass",116        "module_name": "tests.core.usage_statistics.test_anonymizer",117    }118    classes_to_check = [TestClass, BaseTestClass]119    assert (120        anonymizer.get_parent_class(121            classes_to_check=classes_to_check, object_config=my_custom_test_class_config122        )123        == "TestClass"124    )125    assert (126        anonymizer.get_parent_class(127            classes_to_check=classes_to_check, object_config=some_other_class_config128        )129        is None130    )131    classes_to_check = [BaseTestClass]132    assert (133        anonymizer.get_parent_class(134            classes_to_check=classes_to_check, object_config=test_class_config135        )136        == "BaseTestClass"137    )138def test_anonymize_object_info_with_core_ge_object(139    anonymizer_with_consistent_salt: Anonymizer,140):141    anonymized_result: dict = anonymizer_with_consistent_salt._anonymize_object_info(142        anonymized_info_dict={},143        object_=ExpectationSuite(expectation_suite_name="my_suite"),144    )145    assert anonymized_result == {"parent_class": "ExpectationSuite"}146def test_anonymize_object_info_with_custom_user_defined_object_with_single_parent(147    anonymizer_with_consistent_salt: Anonymizer,...get_parent_class.py
Source:get_parent_class.py  
1# coding: utf-82def get_parent_class(cls):3    if not isinstance(cls, type):4        cls = type(cls)5    return cls.__bases__6if __name__ == '__main__':7    class dad(object):8        pass9    class child(dad):10        def __new__(cls, *args, **kwargs):11            print(cls, args, kwargs)12            print("I'm ", get_parent_class(cls), "'s son")13            return object.__new__(cls)14    class child2(dad):15        def __new__(cls, *args, **kwargs):16            print(cls, args, kwargs)17            o = object.__new__(cls)18            print("I'm ", get_parent_class(o), "'s son too")19            return o20    f = child()...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!!
