Exemple #1
0
def list_(request):
    if request.session.get('state', None) == 'success':
        prompt = 'success'
    request.session['state'] = None

    project_list = get_project_list()
    has_sub_object = True
    is_admin = check_admin(request.user)

    page = request.GET.get('page')
    size = request.GET.get('size', request.COOKIES.get('size'))
    search_text = request.GET.get('search_text', '')
    order_by = request.GET.get('order_by', 'pk')
    order_by_reverse = request.GET.get('order_by_reverse', 'True')
    all_ = request.GET.get('all_', 'False')
    search_project = request.GET.get('search_project', None)

    page = change_to_positive_integer(page, 1)
    size = change_to_positive_integer(size, 10)
    if order_by_reverse == 'True':
        order_by_reverse = True
    else:
        order_by_reverse = False
    if all_ == 'False':
        all_ = False
    else:
        all_ = True
    if search_project in ('', 'None'):
        search_project = None

    q = get_query_condition(search_text)
    q &= Q(is_active=True)
    if not all_:
        q &= Q(creator=request.user)
    if search_project:
        q &= Q(project=search_project)

    objects = Suite.objects.filter(q).values(
        'pk', 'uuid', 'name', 'keyword', 'project__name', 'config__name',
        'creator', 'creator__username',
        'modified_date').annotate(real_name=Concat('creator__last_name',
                                                   'creator__first_name',
                                                   output_field=CharField()))
    m2m_objects = Suite.objects.filter(
        is_active=True,
        case__is_active=True).values('pk').annotate(m2m_count=Count('case'))
    m2m_count = {o['pk']: o['m2m_count'] for o in m2m_objects}
    result_objects = Suite.objects.filter(
        is_active=True, suiteresult__is_active=True).values('pk').annotate(
            result_count=Count('suiteresult'))
    result_count = {o['pk']: o['result_count'] for o in result_objects}
    for o in objects:
        o['m2m_count'] = m2m_count.get(o['pk'], 0)
        o['result_count'] = result_count.get(o['pk'], 0)
    # 排序
    if objects:
        if order_by not in objects[0]:
            order_by = 'pk'
        objects = sorted(objects,
                         key=lambda x: x[order_by],
                         reverse=order_by_reverse)
    paginator = Paginator(objects, size)
    try:
        objects = paginator.page(page)
    except PageNotAnInteger:
        objects = paginator.page(1)
        page = 1
    except EmptyPage:
        objects = paginator.page(paginator.num_pages)
        page = paginator.num_pages
    order_by_form = OrderByForm(initial={
        'order_by': order_by,
        'order_by_reverse': order_by_reverse
    })
    paginator_form = PaginatorForm(initial={
        'page': page,
        'size': size
    },
                                   page_max_value=paginator.num_pages)
    # 设置cookie
    cookies = [Cookie('size', size, path=request.path)]
    respond = render(request, 'main/suite/list.html', locals())
    for cookie in cookies:
        respond.set_cookie(cookie.key, cookie.value, cookie.max_age,
                           cookie.expires, cookie.path)
    return respond
Exemple #2
0
def detail(request, pk):
    next_ = request.GET.get('next', '')
    inside = request.GET.get('inside')
    new_pk = request.GET.get('new_pk')
    project_list = get_project_list()
    has_sub_object = True
    is_admin = check_admin(request.user)

    try:
        obj = Suite.objects.select_related('creator', 'modifier').get(pk=pk)
    except Suite.DoesNotExist:
        raise Http404('Suite does not exist')

    if request.method == 'POST' and (is_admin or request.user == obj.creator):
        obj_temp = copy.deepcopy(obj)
        form = SuiteForm(data=request.POST, instance=obj_temp)
        try:
            m2m_list = json.loads(request.POST.get('case', 'null'))
        except json.decoder.JSONDecodeError:
            logger.warning('无法获取m2m值', exc_info=True)
            m2m_list = None
        if form.is_valid():
            obj_temp = form.save(commit=False)
            obj_temp.modifier = request.user
            obj_temp.save()
            if m2m_list is not None:
                m2m = SuiteVsCase.objects.filter(suite=obj).order_by('order')
                original_m2m_list = list()
                for dict_ in m2m.values('case'):
                    original_m2m_list.append(str(dict_['case']))
                if original_m2m_list != m2m_list:
                    m2m.delete()
                    order = 0
                    for m2m_pk in m2m_list:
                        if m2m_pk is None or m2m_pk.strip() == '':
                            continue
                        try:
                            m2m_obj = Case.objects.get(pk=m2m_pk)
                        except Case.DoesNotExist:
                            logger.warning('找不到m2m对象[{}]'.format(m2m_pk),
                                           exc_info=True)
                            continue
                        order += 1
                        SuiteVsCase.objects.create(suite=obj,
                                                   case=m2m_obj,
                                                   order=order,
                                                   creator=request.user,
                                                   modifier=request.user)
            request.session['state'] = 'success'
            _redirect = request.POST.get('redirect')
            if _redirect:
                if _redirect == 'close':
                    request.session['state'] = None
                    return render(request, 'main/other/close.html')
                if not next_:
                    next_ = reverse(list_)
                    request.session['state'] = None
                return HttpResponseRedirect(next_)
            else:
                return HttpResponseRedirect(request.get_full_path())
        else:
            temp_config = request.POST.get('config')
            if m2m_list is not None:
                # 暂存step列表
                m2m = SuiteVsCase.objects.filter(suite=obj).order_by('order')
                original_m2m_list = list()
                for dict_ in m2m.values('case'):
                    original_m2m_list.append(str(dict_['case']))
                temp_list = list()
                temp_dict = dict()
                if original_m2m_list != m2m_list:
                    temp_list_json = json.dumps(m2m_list)

        return render(request, 'main/suite/detail.html', locals())
    else:
        form = SuiteForm(instance=obj)
        if request.session.get('state', None) == 'success':
            prompt = 'success'
        request.session['state'] = None
        return render(request, 'main/suite/detail.html', locals())
Exemple #3
0
def add(request):
    next_ = request.GET.get('next', '')
    inside = request.GET.get('inside')
    project_list = get_project_list()

    if request.method == 'POST':
        form = SuiteForm(data=request.POST)
        try:
            m2m_list = json.loads(request.POST.get('case', 'null'))
        except json.decoder.JSONDecodeError:
            logger.warning('无法获取m2m值', exc_info=True)
            m2m_list = None
        if form.is_valid():
            obj_temp = form.save(commit=False)
            obj_temp.creator = obj_temp.modifier = request.user
            obj_temp.save()
            obj = obj_temp
            pk = obj.id
            if m2m_list is not None:
                order = 0
                for m2m_pk in m2m_list:
                    if m2m_pk is None or m2m_pk.strip() == '':
                        continue
                    try:
                        m2m_obj = Case.objects.get(pk=m2m_pk)
                    except Case.DoesNotExist:
                        logger.warning('找不到m2m对象[{}]'.format(m2m_pk),
                                       exc_info=True)
                        continue
                    order += 1
                    SuiteVsCase.objects.create(suite=obj,
                                               case=m2m_obj,
                                               order=order,
                                               creator=request.user,
                                               modifier=request.user)
            request.session['state'] = 'success'
            _redirect = request.POST.get('redirect')
            if _redirect == 'add_another':
                return HttpResponseRedirect(request.get_full_path())
            elif _redirect:
                if _redirect == 'close':
                    request.session['state'] = None
                    return render(request, 'main/other/close.html')
                if not next_:
                    next_ = reverse(list_)
                    request.session['state'] = None
                return HttpResponseRedirect(next_)
            else:
                para = ''
                if inside:  # 如果是内嵌网页,则加上内嵌标志后再跳转
                    para = '&inside=1&new_pk={}'.format(pk)
                return HttpResponseRedirect('{}?next={}{}'.format(
                    reverse(detail, args=[pk]), quote(next_), para))
        else:
            temp_config = request.POST.get('config')
            temp_variable_group = request.POST.get('variable_group')
            temp_config = request.POST.get('config')
            if m2m_list is not None:
                temp_list_json = json.dumps(m2m_list)

        return render(request, 'main/suite/detail.html', locals())
    else:
        form = SuiteForm()
        if request.session.get('state', None) == 'success':
            prompt = 'success'
        request.session['state'] = None
        return render(request, 'main/suite/detail.html', locals())
def list_(request):
    if request.session.get('state', None) == 'success':
        prompt = 'success'
    request.session['state'] = None

    project_list = get_project_list()
    is_admin = check_admin(request.user)

    page = request.GET.get('page')
    size = request.GET.get('size', request.COOKIES.get('size'))
    search_text = request.GET.get('search_text', '')
    order_by = request.GET.get('order_by', 'pk')
    order_by_reverse = request.GET.get('order_by_reverse', 'True')
    all_ = request.GET.get('all_', 'False')
    search_project = request.GET.get('search_project', None)
    suite_id = request.GET.get('suite_id', None)

    page = change_to_positive_integer(page, 1)
    size = change_to_positive_integer(size, 10)
    if order_by_reverse == 'True':
        order_by_reverse = True
    else:
        order_by_reverse = False
    if all_ == 'False':
        all_ = False
    else:
        all_ = True
    if search_project in ('', 'None'):
        search_project = None

    q = get_query_condition(search_text)
    q &= Q(is_active=True)
    if not all_:
        q &= Q(creator=request.user)
    if search_project:
        q &= Q(project=search_project)
    if suite_id:
        try:
            obj = Suite.objects.get(pk=suite_id)
        except Suite.DoesNotExist:
            raise Http404('Suite does not exist')
        q &= Q(suite=obj)

    objects = SuiteResult.objects.filter(q).values(
        'pk', 'uuid', 'name', 'keyword', 'project__name', 'creator',
        'creator__username', 'modified_date', 'suite__pk', 'start_date',
        'end_date',
        'result_state').annotate(real_name=Concat('creator__last_name',
                                                  'creator__first_name',
                                                  output_field=CharField()))

    d = {l[0]: l[1] for l in result_state_list}
    m2m_objects = SuiteResult.objects.filter(
        # is_active=True, caseresult__case_order__isnull=False).values('pk').annotate(
        is_active=True,
        caseresult__step_result__isnull=True).values('pk').annotate(
            m2m_count=Count('caseresult'))
    m2m_count = {o['pk']: o['m2m_count'] for o in m2m_objects}
    for o in objects:
        # 获取状态文字
        o['result_state_str'] = d.get(o['result_state'], 'N/A')
        # 获取耗时
        # 为了减少查询数据库,没有使用models里的方法
        if o['end_date'] is None or o['start_date'] is None:
            o['elapsed_time'] = datetime.timedelta(days=9999)
        else:
            o['elapsed_time'] = o['end_date'] - o['start_date']
        if o['elapsed_time'] >= datetime.timedelta(days=9999):
            o['elapsed_time_str'] = 'N/A'
        else:
            o['elapsed_time_str'] = get_timedelta_str(o['elapsed_time'], 1)
        # 获取子对象数量
        o['m2m_count'] = m2m_count.get(o['pk'], 0)
    # 排序
    if objects:
        if order_by not in objects[0]:
            order_by = 'pk'
        objects = sorted(objects,
                         key=lambda x: x[order_by],
                         reverse=order_by_reverse)
    paginator = Paginator(objects, size)
    try:
        objects = paginator.page(page)
    except PageNotAnInteger:
        objects = paginator.page(1)
        page = 1
    except EmptyPage:
        objects = paginator.page(paginator.num_pages)
        page = paginator.num_pages
    order_by_form = OrderByForm(initial={
        'order_by': order_by,
        'order_by_reverse': order_by_reverse
    })
    paginator_form = PaginatorForm(initial={
        'page': page,
        'size': size
    },
                                   page_max_value=paginator.num_pages)
    # 设置cookie
    cookies = [Cookie('size', size, path=request.path)]
    respond = render(request, 'main/result/list.html', locals())
    for cookie in cookies:
        respond.set_cookie(cookie.key, cookie.value, cookie.max_age,
                           cookie.expires, cookie.path)
    return respond