Ejemplo n.º 1
0
    def test_create(self):
        values = {
            'summary': f'Test new case: {self.__class__.__name__}',
            'is_automated': True,
            'is_automated_proposed': True,
            'script': '',
            'arguments': '',
            'extra_link': 'https://localhost/case-2',
            'requirement': '',
            'alias': 'alias',
            'estimated_time': 0,
            'case_status': TestCaseStatus.objects.get(name='CONFIRMED'),
            'category': TestCaseCategory.objects.all()[0],
            'priority': Priority.objects.all()[0],
            'default_tester': self.tester,
            'notes': '',
            'tag': [self.tag_fedora, self.tag_python],
            'component': [self.component_db, self.component_web],
        }
        TestCase.create(self.tester, values=values, plans=[self.plan])

        new_case = TestCase.objects.get(summary=values['summary'])

        expected = values.copy()
        expected['estimated_time'] = timedelta(0)

        from tests.testcases import assert_new_case
        assert_new_case(new_case, expected)

        self.assertTrue(
            TestCasePlan.objects.filter(plan=self.plan,
                                        case=new_case).exists())
Ejemplo n.º 2
0
def update(request, case_ids, values):
    """Updates the fields of the selected case or cases.

                 $values   - Hash of keys matching TestCase fields and the new values
                             to set each field to.

    :param case_ids: give one or more case IDs. It could be an integer, a
        string containing comma separated IDs, or a list of int each of them is
        a case ID.
    :type case_ids: int, str or list
    :param dict values: a mapping containing these case data to update.

        * case_status: (ini) optional
        * product: (ini) optional (Required if changes category)
        * category: (ini) optional
        * priority: (ini) optional
        * default_tester: (str or int) optional (str - user_name, int - user_id)
        * estimated_time: (str) optional (2h30m30s(recommend) or HH:MM:SS
        * is_automated: (ini) optional (0 - Manual, 1 - Auto, 2 - Both)
        * is_automated_proposed: (bool) optional
        * script: (str) optional
        * arguments: (str) optional
        * summary: (str) optional
        * requirement: (str) optional
        * alias: (str) optional
        * notes: (str) optional
        * extra_link: (str) optional (reference link)

    :return: a list of mappings of updated :class:`TestCase`.
    :rtype: list(dict)

    Example::

        # Update alias to 'tcms' for case 1 and 2
        TestCase.update([1, 2], {'alias': 'tcms'})
    """
    from tcms.core import forms
    from tcms.xmlrpc.forms import UpdateCaseForm

    if values.get('estimated_time'):
        values['estimated_time'] = pre_process_estimated_time(values.get('estimated_time'))

    form = UpdateCaseForm(values)

    if values.get('category') and not values.get('product'):
        raise ValueError('Product ID is required for category')

    if values.get('product'):
        form.populate(product_id=values['product'])

    if form.is_valid():
        tcs = TestCase.update(
            case_ids=pre_process_ids(value=case_ids),
            values=form.cleaned_data,
        )
    else:
        raise ValueError(forms.errors_to_list(form))

    query = {'pk__in': tcs.values_list('pk', flat=True)}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 3
0
def update(request, case_ids, values):
    """Updates the fields of the selected case or cases.

                 $values   - Hash of keys matching TestCase fields and the new values
                             to set each field to.

    :param case_ids: give one or more case IDs. It could be an integer, a
        string containing comma separated IDs, or a list of int each of them is
        a case ID.
    :type case_ids: int, str or list
    :param dict values: a mapping containing these case data to update.

        * case_status: (ini) optional
        * product: (ini) optional (Required if changes category)
        * category: (ini) optional
        * priority: (ini) optional
        * default_tester: (str or int) optional (str - user_name, int - user_id)
        * estimated_time: (str) optional (2h30m30s(recommend) or HH:MM:SS
        * is_automated: (ini) optional (0 - Manual, 1 - Auto, 2 - Both)
        * is_automated_proposed: (bool) optional
        * script: (str) optional
        * arguments: (str) optional
        * summary: (str) optional
        * requirement: (str) optional
        * alias: (str) optional
        * notes: (str) optional
        * extra_link: (str) optional (reference link)

    :return: a list of mappings of updated :class:`TestCase`.
    :rtype: list(dict)

    Example::

        # Update alias to 'tcms' for case 1 and 2
        >>> TestCase.update([1, 2], {'alias': 'tcms'})
    """
    from tcms.core import forms
    from tcms.xmlrpc.forms import UpdateCaseForm

    if values.get('estimated_time'):
        values['estimated_time'] = pre_process_estimated_time(values.get('estimated_time'))

    form = UpdateCaseForm(values)

    if values.get('category') and not values.get('product'):
        raise ValueError('Product ID is required for category')

    if values.get('product'):
        form.populate(product_id=values['product'])

    if form.is_valid():
        tcs = TestCase.update(
            case_ids=pre_process_ids(value=case_ids),
            values=form.cleaned_data,
        )
    else:
        raise ValueError(forms.errors_to_list(form))

    query = {'pk__in': tcs.values_list('pk', flat=True)}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 4
0
def query_testcases_from_request(request, plan=None):
    """Query TestCases according to criterias coming within REQUEST

    :param request: the REQUEST object.
    :param plan: instance of TestPlan to restrict only those TestCases belongs to
                 the TestPlan. Can be None. As you know, query from all TestCases.
    """
    search_form = build_cases_search_form(request)

    action = request.POST.get('a')
    if action == 'initial':
        # todo: build_cases_search_form will also check TESTCASE_OPERATION_ACTIONS
        # and return slightly different values in case of initialization
        # move the check there and just execute the query here if the data
        # is valid
        d_status = get_case_status(request.POST.get('template_type'))
        tcs = TestCase.objects.filter(case_status__in=d_status)
    elif action in TESTCASE_OPERATION_ACTIONS and search_form.is_valid():
        tcs = TestCase.list(search_form.cleaned_data, plan)
    else:
        tcs = TestCase.objects.none()

    # Search the relationship
    if plan:
        tcs = tcs.filter(plan=plan)

    tcs = tcs.select_related('author', 'default_tester', 'case_status',
                             'priority', 'category', 'reviewer')
    return tcs, search_form
Ejemplo n.º 5
0
    def post(self, request, plan_id):
        plan = get_object_or_404(TestPlan, pk=int(plan_id))

        search_mode = request.POST.get('search_mode')
        if search_mode == 'quick':
            form = quick_form = QuickSearchCaseForm(request.POST)
            normal_form = SearchCaseForm()
        else:
            form = normal_form = SearchCaseForm(request.POST)
            form.populate(product_id=request.POST.get('product'))
            quick_form = QuickSearchCaseForm()

        if form.is_valid():
            cases = TestCase.list(form.cleaned_data)
            cases = cases.select_related(
                'author', 'default_tester', 'case_status', 'priority'
            ).only(
                'pk', 'summary', 'create_date', 'author__email',
                'default_tester__email', 'case_status__name',
                'priority__value'
            ).exclude(
                case_id__in=plan.case.values_list('case_id', flat=True))

        context = {
            'module': MODULE_NAME,
            'sub_module': self.SUB_MODULE_NAME,
            'test_plan': plan,
            'test_cases': cases,
            'search_form': normal_form,
            'quick_form': quick_form,
            'search_mode': search_mode
        }
        return render(request, self.template_name, context=context)
Ejemplo n.º 6
0
 def test_list_by_multiple_criteria(self):
     cases = TestCase.list({
         'category':
         TestCaseCategory.objects.get(name='functional'),
         'issue_key': ['2000'],
     })
     self.assertEqual([self.case_1], list(cases))
Ejemplo n.º 7
0
def query_testcases_from_request(request, plan=None):  # pylint: disable=missing-permission-required
    """Query TestCases according to criterias coming within REQUEST

    :param request: the REQUEST object.
    :type request: :class:`django.http.HttpRequest`

    :param plan: instance of TestPlan to restrict only those TestCases belongs to
                 the TestPlan. Can be None. As you know, query from all TestCases.
    :type plan: :class:`tcms.testplans.models.TestPlan`

    :return: Queryset with testcases and search form
    :rtype: :class:`django.db.models.query.QuerySet`, dict
    """
    search_form = build_cases_search_form(request, True, plan)

    action = request.POST.get('a')
    if action == 'initial':
        # todo: build_cases_search_form will also check TESTCASE_OPERATION_ACTIONS
        # and return slightly different values in case of initialization
        # move the check there and just execute the query here if the data
        # is valid
        d_status = get_case_status(request.POST.get('template_type'))
        tcs = TestCase.objects.filter(case_status__in=d_status)
    elif action in TESTCASE_OPERATION_ACTIONS and search_form.is_valid():
        tcs = TestCase.list(search_form.cleaned_data, plan)
    else:
        tcs = TestCase.objects.none()

    # Search the relationship
    if plan:
        tcs = tcs.filter(plan=plan)

    tcs = tcs.select_related('author', 'default_tester', 'case_status',
                             'priority', 'category', 'reviewer')
    return tcs, search_form
Ejemplo n.º 8
0
    def post(self, request, plan_id):
        plan = get_object_or_404(TestPlan, pk=int(plan_id))

        search_mode = request.POST.get('search_mode')
        if search_mode == 'quick':
            form = quick_form = QuickSearchCaseForm(request.POST)
            normal_form = SearchCaseForm()
        else:
            form = normal_form = SearchCaseForm(request.POST)
            form.populate(product_id=request.POST.get('product'))
            quick_form = QuickSearchCaseForm()

        cases = []
        if form.is_valid():
            cases = TestCase.list(form.cleaned_data)
            cases = cases.select_related(
                'author', 'default_tester', 'case_status', 'priority'
            ).only(
                'pk', 'summary', 'create_date', 'author__email',
                'default_tester__email', 'case_status__name',
                'priority__value'
            ).exclude(
                case_id__in=plan.case.values_list('case_id', flat=True))

        context = {
            'test_plan': plan,
            'test_cases': cases,
            'search_form': normal_form,
            'quick_form': quick_form,
            'search_mode': search_mode
        }
        return render(request, self.template_name, context=context)
Ejemplo n.º 9
0
def create(values, **kwargs):
    """
    .. function:: XML-RPC TestCase.create(values)

        Create a new TestCase object and store it in the database.

        :param values: Field values for :class:`tcms.testcases.models.TestCase`
        :type values: dict
        :return: Serialized :class:`tcms.testcases.models.TestCase` object
        :rtype: dict
        :raises: PermissionDenied if missing *testcases.add_testcase* permission

        Minimal test case parameters::

            >>> values = {
                'category': 135,
                'product': 61,
            'summary': 'Testing XML-RPC',
            'priority': 1,
            }
            >>> TestCase.create(values)
    """
    request = kwargs.get(REQUEST_KEY)

    if not (values.get('category') or values.get('summary')):
        raise ValueError()

    if values.get('estimated_time'):
        values['estimated_time'] = parse_duration(values.get('estimated_time'))

    form = NewCaseForm(values)
    form.populate(values.get('product'))

    if form.is_valid():
        # Create the case
        test_case = TestCase.create(author=request.user,
                                    values=form.cleaned_data)

        # Add case text to the case
        test_case.add_text(
            action=form.cleaned_data['action'] or '',
            effect=form.cleaned_data['effect'] or '',
            setup=form.cleaned_data['setup'] or '',
            breakdown=form.cleaned_data['breakdown'] or '',
        )

        # Add tag to the case
        for tag in string_to_list(values.get('tag', [])):
            tag, _ = Tag.objects.get_or_create(name=tag)
            test_case.add_tag(tag=tag)
    else:
        # Print the errors if the form is not passed validation.
        raise ValueError(form_errors_to_list(form))

    result = test_case.serialize()
    result['text'] = test_case.latest_text().serialize()

    return result
Ejemplo n.º 10
0
        def link_cases(self, template_name='plan/search_case.html'):
            """Handle to form to add case to plans"""
            SUB_MODULE_NAME = 'plans'
            tcs = None

            if request.POST.get('action') == 'add_to_plan':
                if request.user.has_perm('testcases.add_testcaseplan'):
                    tcs = TestCase.objects.filter(
                        case_id__in=request.POST.getlist('case'))
                    for tc in tcs:
                        tp.add_case(tc)
                else:
                    return HttpResponse("Permission Denied")

                return HttpResponseRedirect(
                    reverse('test_plan_url_short', args=[plan_id]))

            search_mode = request.POST.get('search_mode')
            if request.POST.get('action') == 'search':

                if search_mode == 'quick':
                    form = quick_form = QuickSearchCaseForm(request.POST)
                    normal_form = SearchCaseForm()
                else:
                    form = normal_form = SearchCaseForm(request.POST)
                    form.populate(product_id=request.POST.get('product'))
                    quick_form = QuickSearchCaseForm()

                if form.is_valid():
                    tcs = TestCase.list(form.cleaned_data)
                    tcs = tcs.select_related(
                        'author', 'default_tester', 'case_status',
                        'priority').only('pk', 'summary', 'create_date',
                                         'author__email',
                                         'default_tester__email',
                                         'case_status__name',
                                         'priority__value')
                    tcs = tcs.exclude(
                        case_id__in=tp.case.values_list('case_id', flat=True))
            else:
                normal_form = SearchCaseForm(
                    initial={
                        'product': tp.product_id,
                        'product_version': tp.product_version_id,
                        'case_status_id': TestCaseStatus.get_CONFIRMED()
                    })
                quick_form = QuickSearchCaseForm()

            context_data = {
                'module': MODULE_NAME,
                'sub_module': SUB_MODULE_NAME,
                'test_plan': tp,
                'test_cases': tcs,
                'search_form': normal_form,
                'quick_form': quick_form,
                'search_mode': search_mode
            }
            return render(request, template_name, context_data)
Ejemplo n.º 11
0
    def _sendmail(self):
        mail_context = TestCase.mail_scene(objects=self._update_objects,
                                           field=self.target_field,
                                           value=self.new_value)
        if mail_context:
            from tcms.core.utils.mailto import mailto

            mail_context['context']['user'] = self.request.user
            mailto(**mail_context)
Ejemplo n.º 12
0
    def _sendmail(self):
        mail_context = TestCase.mail_scene(objects=self._update_objects,
                                           field=self.target_field,
                                           value=self.new_value)
        if mail_context:
            from tcms.core.mailto import mailto

            mail_context['context']['user'] = self.request.user
            mailto(**mail_context)
Ejemplo n.º 13
0
Archivo: ajax.py Proyecto: urba1n/Kiwi
    def _sendmail(self):
        mail_context = TestCase.mail_scene(objects=self._update_objects,
                                           field=self.target_field)
        if mail_context:
            from tcms.core.utils.mailto import mailto

            mail_context['context']['user'] = self.request.user
            try:
                mailto(**mail_context)
            except Exception:  # nosec:B110:try_except_pass
                pass
Ejemplo n.º 14
0
    def create_test_case(self, form, notify_form, test_plan):
        """Create new test case"""
        test_case = TestCase.create(author=self.request.user, values=form.cleaned_data)

        # Assign the case to the plan
        if test_plan:
            test_plan.add_case(test_case)

        update_case_email_settings(test_case, notify_form)

        return test_case
Ejemplo n.º 15
0
        def link_cases(self, template_name='plan/search_case.html'):
            """Handle to form to add case to plans"""
            SUB_MODULE_NAME = 'plans'
            tcs = None

            if request.POST.get('action') == 'add_to_plan':
                if request.user.has_perm('testcases.add_testcaseplan'):
                    tcs = TestCase.objects.filter(case_id__in=request.POST.getlist('case'))
                    for tc in tcs:
                        tp.add_case(tc)
                else:
                    return HttpResponse("Permission Denied")

                return HttpResponseRedirect(
                    reverse('tcms.testplans.views.get', args=[plan_id]))

            search_mode = request.POST.get('search_mode')
            if request.POST.get('action') == 'search':

                if search_mode == 'quick':
                    form = quick_form = QuickSearchCaseForm(request.POST)
                    normal_form = SearchCaseForm()
                else:
                    form = normal_form = SearchCaseForm(request.POST)
                    form.populate(product_id=request.POST.get('product'))
                    quick_form = QuickSearchCaseForm()

                if form.is_valid():
                    tcs = TestCase.list(form.cleaned_data)
                    tcs = tcs.select_related(
                        'author', 'default_tester', 'case_status', 'priority').only(
                            'pk', 'summary', 'create_date', 'author__email',
                            'default_tester__email', 'case_status__name', 'priority__value')
                    tcs = tcs.exclude(case_id__in=tp.case.values_list('case_id', flat=True))
            else:
                normal_form = SearchCaseForm(initial={
                    'product': tp.product_id,
                    'product_version': tp.product_version_id,
                    'case_status_id': TestCaseStatus.get_CONFIRMED()
                })
                quick_form = QuickSearchCaseForm()

            context_data = {
                'module': MODULE_NAME,
                'sub_module': SUB_MODULE_NAME,
                'test_plan': tp,
                'test_cases': tcs,
                'search_form': normal_form,
                'quick_form': quick_form,
                'search_mode': search_mode
            }
            return render_to_response(template_name, context_data,
                                      context_instance=RequestContext(request))
Ejemplo n.º 16
0
def create_testcase(request, form, test_plan):
    """Create testcase"""
    test_case = TestCase.create(author=request.user, values=form.cleaned_data)

    # Assign the case to the plan
    if test_plan:
        test_plan.add_case(test_case)

    # Add components into the case
    for component in form.cleaned_data['component']:
        test_case.add_component(component=component)
    return test_case
Ejemplo n.º 17
0
    def test_list_by_search_keyword(self):
        criteria = [
            {
                'search': 'Test list'
            },
            {
                'search': self.case_author.email.split('@')[0]
            },
        ]

        for item in criteria:
            cases = TestCase.list(item)
            self.assertEqual([self.case_1], list(cases))
Ejemplo n.º 18
0
def filter(request, query):
    """
    Description: Performs a search and returns the resulting list of test cases.

    Params:      $query - Hash: keys must match valid search fields.

        +------------------------------------------------------------------+
        |                 Case Search Parameters                           |
        +------------------------------------------------------------------+
        |        Key          |          Valid Values                      |
        | author              | A bugzilla login (email address)           |
        | attachment          | ForeignKey: Attchment                      |
        | alias               | String                                     |
        | case_id             | Integer                                    |
        | case_status         | ForeignKey: Case Stat                      |
        | category            | ForeignKey: Category                       |
        | component           | ForeignKey: Component                      |
        | default_tester      | ForeignKey: Auth.User                      |
        | estimated_time      | String: 2h30m30s(recommend) or HH:MM:SS    |
        | plan                | ForeignKey: Test Plan                      |
        | priority            | ForeignKey: Priority                       |
        | category__product   | ForeignKey: Product                        |
        | summary             | String                                     |
        | tags                | ForeignKey: Tags                           |
        | create_date         | Datetime                                   |
        | is_automated        | 1: Only show current 0: show not current   |
        | script              | Text                                       |
        +------------------------------------------------------------------+

    Returns:     Array: Matching test cases are retuned in a list of hashes.

    Example:
    # Get all of cases contain 'TCMS' in summary
    >>> TestCase.filter({'summary__icontain': 'TCMS'})
    # Get all of cases create by xkuang
    >>> TestCase.filter({'author__username': '******'})
    # Get all of cases the author name starts with x
    >>> TestCase.filter({'author__username__startswith': 'x'})
    # Get all of cases belong to the plan 137
    >>> TestCase.filter({'plan__plan_id': 137})
    # Get all of cases belong to the plan create by xkuang
    >>> TestCase.filter({'plan__author__username': '******'})
    # Get cases with ID 12345, 23456, 34567 - Here is only support array so far.
    >>> TestCase.filter({'case_id__in': [12345, 23456, 34567]})
    """
    if query.get('estimated_time'):
        query['estimated_time'] = timedelta2int(
            pre_process_estimated_time(query.get('estimated_time'))
        )

    return TestCase.to_xmlrpc(query)
Ejemplo n.º 19
0
    def test_update(self):
        TestCase.update(
            self.case_1.pk, {
                'category':
                f.TestCaseCategoryFactory(name='functional',
                                          product=self.product),
                'is_automated':
                1,
                'notes':
                '',
                'script':
                '',
            })

        case = TestCase.objects.get(pk=self.case_1.pk)

        category = TestCaseCategory.objects.get(name='functional',
                                                product=self.product)

        self.assertEqual(category, case.category)
        self.assertEqual(1, case.is_automated)
        self.assertEqual('', case.notes)
        self.assertEqual('', case.script)
Ejemplo n.º 20
0
    def test_simple_list_by_property(self):
        criteria = [
            {
                'summary': 'list case'
            },
            {
                'author': self.case_1.author.username
            },
            {
                'author': self.case_1.author.email
            },
            {
                'default_tester': self.case_1.default_tester.username
            },
            {
                'default_tester': self.case_1.default_tester.email
            },
            {
                'tag__name__in': ['python']
            },
            {
                'category': TestCaseCategory.objects.get(name='functional')
            },
            {
                'priority': [Priority.objects.get(value='P3')]
            },
            {
                'case_status': [TestCaseStatus.objects.first()]
            },
            {
                'component': Component.objects.get(name='db')
            },
            {
                'is_automated': 1
            },
            {
                'is_automated_proposed': True
            },
            {
                'product': self.product.pk
            },
            {
                'issue_key': ['2000', '1000']
            },
        ]

        for item in criteria:
            cases = TestCase.list(item)
            self.assertEqual([self.case_1], list(cases))
Ejemplo n.º 21
0
def filter(query=None):  # pylint: disable=redefined-builtin
    """
    .. function:: XML-RPC TestCase.filter(query)

        Perform a search and return the resulting list of test cases
        augmented with their latest ``text``.

        :param query: Field lookups for :class:`tcms.testcases.models.TestCase`
        :type query: dict
        :return: Serialized list of :class:`tcms.testcases.models.TestCase` objects.
        :rtype: list(dict)
    """
    if query is None:
        query = {}

    return TestCase.to_xmlrpc(query)
Ejemplo n.º 22
0
def filter(request, query):
    """Performs a search and returns the resulting list of test cases.

    :param dict query: a mapping containing these criteria.

        * author: A Bugzilla login (email address)
        * attachment: ForeignKey: Attachment
        * alias: (str)
        * case_id: (int)
        * case_status: ForeignKey: Case Stat
        * category: ForeignKey: :class:`Category`
        * component: ForeignKey: :class:`Component`
        * default_tester: ForeignKey: ``Auth.User``
        * estimated_time: String: 2h30m30s(recommend) or HH:MM:SS
        * plan: ForeignKey: :class:`TestPlan`
        * priority: ForeignKey: :class:`Priority`
        * category__product: ForeignKey: :class:`Product`
        * summary: (str)
        * tags: ForeignKey: :class:`Tags`
        * create_date: Datetime
        * is_automated: 1: Only show current 0: show not current
        * script: (str)

    :return: list of mappings of found :class:`TestCase`.
    :rtype: list

    Example::

        # Get all of cases contain 'TCMS' in summary
        >>> TestCase.filter({'summary__icontain': 'TCMS'})
        # Get all of cases create by xkuang
        >>> TestCase.filter({'author__username': '******'})
        # Get all of cases the author name starts with x
        >>> TestCase.filter({'author__username__startswith': 'x'})
        # Get all of cases belong to the plan 1
        >>> TestCase.filter({'plan__plan_id': 1})
        # Get all of cases belong to the plan create by xkuang
        >>> TestCase.filter({'plan__author__username': '******'})
        # Get cases with ID 12345, 23456, 34567 - Here is only support array so far.
        >>> TestCase.filter({'case_id__in': [12345, 23456, 34567]})
    """
    if query.get('estimated_time'):
        query['estimated_time'] = timedelta2int(
            pre_process_estimated_time(query.get('estimated_time'))
        )

    return TestCase.to_xmlrpc(query)
Ejemplo n.º 23
0
def filter(request, query):
    """Performs a search and returns the resulting list of test cases.

    :param dict query: a mapping containing these criteria.

        * author: A Bugzilla login (email address)
        * attachments: ForeignKey: Attachment
        * alias: (str)
        * case_id: (int)
        * case_status: ForeignKey: Case Stat
        * category: ForeignKey: :class:`Category`
        * component: ForeignKey: :class:`Component`
        * default_tester: ForeignKey: ``Auth.User``
        * estimated_time: String: 2h30m30s(recommend) or HH:MM:SS
        * plan: ForeignKey: :class:`TestPlan`
        * priority: ForeignKey: :class:`Priority`
        * category__product: ForeignKey: :class:`Product`
        * summary: (str)
        * tags: ForeignKey: :class:`Tags`
        * create_date: Datetime
        * is_automated: 1: Only show current 0: show not current
        * script: (str)

    :return: list of mappings of found :class:`TestCase`.
    :rtype: list

    Example::

        # Get all of cases contain 'TCMS' in summary
        TestCase.filter({'summary__icontain': 'TCMS'})
        # Get all of cases create by xkuang
        TestCase.filter({'author__username': '******'})
        # Get all of cases the author name starts with x
        TestCase.filter({'author__username__startswith': 'x'})
        # Get all of cases belong to the plan 1
        TestCase.filter({'plan__plan_id': 1})
        # Get all of cases belong to the plan create by xkuang
        TestCase.filter({'plan__author__username': '******'})
        # Get cases with ID 12345, 23456, 34567 - Here is only support array so far.
        TestCase.filter({'case_id__in': [12345, 23456, 34567]})
    """
    if query.get('estimated_time'):
        query['estimated_time'] = timedelta2int(
            pre_process_estimated_time(query.get('estimated_time'))
        )
    deprecate_critetion_attachment(query)
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 24
0
def create_testcase(request, form, test_plan):
    """Create testcase"""
    test_case = TestCase.create(author=request.user, values=form.cleaned_data)
    test_case.add_text(case_text_version=1,
                       author=request.user,
                       action=form.cleaned_data['action'],
                       effect=form.cleaned_data['effect'],
                       setup=form.cleaned_data['setup'],
                       breakdown=form.cleaned_data['breakdown'])

    # Assign the case to the plan
    if test_plan:
        test_case.add_to_plan(plan=test_plan)

    # Add components into the case
    for component in form.cleaned_data['component']:
        test_case.add_component(component=component)
    return test_case
Ejemplo n.º 25
0
def get_cases(request, product):
    """Get the list of cases associated with this product.

    :param product: product ID or name.
    :type product: int or str
    :return: a list of mappings of :class:`TestCase`.

    Example::

        # Get with product id
        >>> Product.get_cases(61)
        # Get with product name
        >>> Product.get_cases('product name')
    """
    from tcms.testcases.models import TestCase

    p = pre_check_product(values=product)
    query = {'category__product': p}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 26
0
def get_cases(request, product):
    """Get the list of cases associated with this product.

    :param product: product ID or name.
    :type product: int or str
    :return: a list of mappings of :class:`TestCase`.

    Example::

        # Get with product id
        >>> Product.get_cases(61)
        # Get with product name
        >>> Product.get_cases('product name')
    """
    from tcms.testcases.models import TestCase

    p = pre_check_product(values=product)
    query = {'category__product': p}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 27
0
def create(values, **kwargs):
    """
    .. function:: XML-RPC TestCase.create(values)

        Create a new TestCase object and store it in the database.

        :param values: Field values for :class:`tcms.testcases.models.TestCase`
        :type values: dict
        :return: Serialized :class:`tcms.testcases.models.TestCase` object
        :rtype: dict
        :raises: PermissionDenied if missing *testcases.add_testcase* permission

        Minimal test case parameters::

            >>> values = {
                'category': 135,
                'product': 61,
            'summary': 'Testing XML-RPC',
            'priority': 1,
            }
            >>> TestCase.create(values)
    """
    request = kwargs.get(REQUEST_KEY)

    if not (values.get('category') or values.get('summary')):
        raise ValueError()

    form = NewCaseForm(values)
    form.populate(values.get('product'))

    if form.is_valid():
        # Create the case
        test_case = TestCase.create(author=request.user,
                                    values=form.cleaned_data)
    else:
        # Print the errors if the form is not passed validation.
        raise ValueError(form_errors_to_list(form))

    result = test_case.serialize()

    return result
Ejemplo n.º 28
0
def get_cases(request, product):
    """
    Description: Get the list of cases associated with this product.

    Params:      $product - Integer/String
                            Integer: product_id of the product in the Database
                            String: Product name

    Returns:     Array: Returns an array of TestCase objects.

    Example:
    # Get with product id
    >>> Product.get_cases(61)
    # Get with product name
    >>> Product.get_cases('Red Hat Enterprise Linux 5')
    """
    from tcms.testcases.models import TestCase

    p = pre_check_product(values=product)
    query = {'category__product': p}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 29
0
def get_cases(request, product):
    """
    Description: Get the list of cases associated with this product.

    Params:      $product - Integer/String
                            Integer: product_id of the product in the Database
                            String: Product name

    Returns:     Array: Returns an array of TestCase objects.

    Example:
    # Get with product id
    >>> Product.get_cases(61)
    # Get with product name
    >>> Product.get_cases('Red Hat Enterprise Linux 5')
    """
    from tcms.testcases.models import TestCase

    p = pre_check_product(values=product)
    query = {'category__product': p}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 30
0
def get_test_cases(request, run_id):
    """Get the list of cases that this run is linked to.

    :param int run_id: run ID.
    :return: a list of mappings of found :class:`TestCase`.
    :rtype: list[dict]

    Example::

        TestRun.get_test_cases(1)
    """
    tcs_serializer = TestCase.to_xmlrpc(query={'case_run__run_id': run_id})

    qs = TestCaseRun.objects.filter(run_id=run_id).values(
        'case', 'pk', 'case_run_status__name')
    extra_info = {row['case']: row for row in qs.iterator()}

    for case in tcs_serializer:
        info = extra_info[case['case_id']]
        case['case_run_id'] = info['pk']
        case['case_run_status'] = info['case_run_status__name']

    return tcs_serializer
Ejemplo n.º 31
0
def get_test_cases(request, run_id):
    """Get the list of cases that this run is linked to.

    :param int run_id: run ID.
    :return: a list of mappings of found :class:`TestCase`.
    :rtype: list[dict]

    Example::

        >>> TestRun.get_test_cases(1)
    """
    tcs_serializer = TestCase.to_xmlrpc(query={'case_run__run_id': run_id})

    qs = TestCaseRun.objects.filter(run_id=run_id).values(
        'case', 'pk', 'case_run_status__name')
    extra_info = dict(((row['case'], row) for row in qs.iterator()))

    for case in tcs_serializer:
        info = extra_info[case['case_id']]
        case['case_run_id'] = info['pk']
        case['case_run_status'] = info['case_run_status__name']

    return tcs_serializer
Ejemplo n.º 32
0
def get_test_cases(request, run_id):
    """
    Description: Get the list of cases that this run is linked to.

    Params:      $run_id - Integer: An integer representing the ID in the database
                                    for this run.

    Returns:     Array: An array of test case object hashes.

    Example:
    >>> TestRun.get_test_cases(1193)
    """
    tcs_serializer = TestCase.to_xmlrpc(query={'case_run__run_id': run_id})

    qs = TestCaseRun.objects.filter(run_id=run_id).values(
        'case', 'pk', 'case_run_status__name')
    extra_info = dict(((row['case'], row) for row in qs.iterator()))

    for case in tcs_serializer:
        info = extra_info[case['case_id']]
        case['case_run_id'] = info['pk']
        case['case_run_status'] = info['case_run_status__name']

    return tcs_serializer
Ejemplo n.º 33
0
def get_test_cases(request, run_id):
    """
    Description: Get the list of cases that this run is linked to.

    Params:      $run_id - Integer: An integer representing the ID in the database
                                    for this run.

    Returns:     Array: An array of test case object hashes.

    Example:
    >>> TestRun.get_test_cases(1193)
    """
    tcs_serializer = TestCase.to_xmlrpc(query={'case_run__run_id': run_id})

    qs = TestCaseRun.objects.filter(run_id=run_id).values(
        'case', 'pk', 'case_run_status__name')
    extra_info = dict(((row['case'], row) for row in qs.iterator()))

    for case in tcs_serializer:
        info = extra_info[case['case_id']]
        case['case_run_id'] = info['pk']
        case['case_run_status'] = info['case_run_status__name']

    return tcs_serializer
Ejemplo n.º 34
0
    def test_to_xmlrpc(self):
        result = TestCase.to_xmlrpc(query={'pk__in': self.case_pks})
        self.assertEqual(len(result), 2)

        # Verify fields
        sample_testcase = result[0]
        sample_fields = set([name for name in sample_testcase.keys()])
        test_fields = set(self.test_fields)
        test_result = list(sample_fields ^ test_fields)
        self.assertEqual(test_result, [])

        result = dict([(item['case_id'], item) for item in result])

        case = result[self.case_pks[0]]
        sample_case = TestCase.objects.get(pk=self.case_pks[0])

        self.assertEqual(case['is_automated'], sample_case.is_automated)
        self.assertEqual(case['summary'], sample_case.summary)
        self.assertEqual(case['alias'], sample_case.alias)

        self.assertEqual(case['author'], sample_case.author.username)
        self.assertEqual(case['author_id'], sample_case.author.pk)
        self.assertEqual(case['priority'], sample_case.priority.value)
        self.assertEqual(case['priority_id'], sample_case.priority.pk)

        components = case['component']
        components.sort()
        sample_components = [item.pk for item in sample_case.component.all()]
        sample_components.sort()
        self.assertEqual(components, sample_components)

        tags = case['tag']
        tags.sort()
        sample_tags = [item.pk for item in sample_case.tag.all()]
        sample_tags.sort()
        self.assertEqual(tags, sample_tags)
Ejemplo n.º 35
0
    def test_to_xmlrpc(self):
        result = TestCase.to_xmlrpc(query={'pk__in': self.case_pks})
        self.assertEqual(len(result), 2)

        # Verify fields
        sample_testcase = result[0]
        sample_fields = set([name for name in sample_testcase.keys()])
        test_fields = set(self.test_fields)
        test_result = list(sample_fields ^ test_fields)
        self.assertEqual(test_result, [])

        result = dict([(item['case_id'], item) for item in result])

        case = result[self.case_pks[0]]
        sample_case = TestCase.objects.get(pk=self.case_pks[0])

        self.assertEqual(case['is_automated'], sample_case.is_automated)
        self.assertEqual(case['summary'], sample_case.summary)
        self.assertEqual(case['alias'], sample_case.alias)

        self.assertEqual(case['author'], sample_case.author.username)
        self.assertEqual(case['author_id'], sample_case.author.pk)
        self.assertEqual(case['priority'], sample_case.priority.value)
        self.assertEqual(case['priority_id'], sample_case.priority.pk)

        components = case['component']
        components.sort()
        sample_components = [item.pk for item in sample_case.component.all()]
        sample_components.sort()
        self.assertEqual(components, sample_components)

        tags = case['tag']
        tags.sort()
        sample_tags = [item.pk for item in sample_case.tag.all()]
        sample_tags.sort()
        self.assertEqual(tags, sample_tags)
Ejemplo n.º 36
0
def assert_new_case(new_case: TestCase, expected: Dict) -> None:
    assert expected['summary'] == new_case.summary
    assert expected['is_automated'] == new_case.is_automated
    assert expected['is_automated_proposed'] == new_case.is_automated_proposed
    assert expected['script'] == new_case.script
    assert expected['arguments'] == new_case.arguments
    assert expected['extra_link'] == new_case.extra_link
    assert expected['notes'] == new_case.notes
    assert expected['default_tester'] == new_case.default_tester
    assert expected['estimated_time'] == new_case.estimated_time
    assert expected['category'] == new_case.category
    assert expected['priority'] == new_case.priority
    assert expected['case_status'] == new_case.case_status
    assert set(expected['tag']) == set(new_case.tag.all())
    assert (sorted(item.pk for item in expected['component']) ==
            sorted(item.pk for item in new_case.component.all()))

    if all(item in expected for item in
           ['action', 'effect', 'setup', 'breakdown']):
        text = new_case.latest_text()
        assert expected['action'] == text.action
        assert expected['effect'] == text.effect
        assert expected['setup'] == text.setup
        assert expected['breakdown'] == text.breakdown
Ejemplo n.º 37
0
def get_cases(run_id):
    """
    .. function:: RPC TestRun.get_cases(run_id)

        Get the list of test cases that are attached to a test run.

        :param run_id: PK of TestRun to inspect
        :type run_id: int
        :return: Serialized list of :class:`tcms.testcases.models.TestCase` objects
                 augmented with ``execution_id`` and ``status`` information.
        :rtype: list(dict)
    """
    tcs_serializer = TestCase.to_xmlrpc(query={'case_run__run_id': run_id})

    qs = TestExecution.objects.filter(run_id=run_id).values(
        'case', 'pk', 'status__name')
    extra_info = dict(((row['case'], row) for row in qs.iterator()))

    for case in tcs_serializer:
        info = extra_info[case['id']]
        case['execution_id'] = info['pk']
        case['status'] = info['status__name']

    return tcs_serializer
Ejemplo n.º 38
0
def create(request, values):
    """Creates a new Test Case object and stores it in the database.

    :param values: a mapping or list of mappings containing these case
        information for creation.

        * product: (int) **Required** ID of Product
        * category: (int) **Required** ID of Category
        * priority: (int) **Required** ID of Priority
        * summary: (str) **Required**
        * case_status: (int) optional ID of case status
        * plan Array/Str/Int optional ID or List of plan_ids
        * component: (int)/str optional ID of Priority
        * default_tester: (str) optional Login of tester
        * estimated_time: (str) optional 2h30m30s(recommend) or HH:MM:SS Format|
        * is_automated: (int) optional 0: Manual, 1: Auto, 2: Both
        * is_automated_proposed: (bool) optional Default 0
        * script: (str) optional
        * arguments: (str) optional
        * requirement: (str) optional
        * alias: (str) optional Must be unique
        * action: (str) optional
        * effect: (str) optional Expected Result
        * setup: (str) optional
        * breakdown: (str) optional
        * tag Array/str optional String Comma separated
        * bug Array/str optional String Comma separated
        * extra_link: (str) optional reference link

    :return: a mapping of newly created test case if a single case was created,
        or a list of mappings of created cases if more than one are created.
    :rtype: dict of list[dict]

    Example::

        # Minimal test case parameters
        >>> values = {
                'category': 1,
                'product': 1,
                'summary': 'Testing XML-RPC',
                'priority': 1,
            }
        >>> TestCase.create(values)
    """
    from tcms.core import forms
    from tcms.xmlrpc.forms import NewCaseForm

    if not (values.get('category') or values.get('summary')):
        raise ValueError()

    values['component'] = pre_process_ids(values.get('component', []))
    values['plan'] = pre_process_ids(values.get('plan', []))
    values['bug'] = pre_process_ids(values.get('bug', []))
    if values.get('estimated_time'):
        values['estimated_time'] = pre_process_estimated_time(values.get('estimated_time'))

    form = NewCaseForm(values)
    form.populate(values.get('product'))

    if form.is_valid():
        # Create the case
        tc = TestCase.create(author=request.user, values=form.cleaned_data)

        # Add case text to the case
        tc.add_text(
            action=form.cleaned_data['action'] or '',
            effect=form.cleaned_data['effect'] or '',
            setup=form.cleaned_data['setup'] or '',
            breakdown=form.cleaned_data['breakdown'] or '',
        )

        # Add the case to specific plans
        for p in form.cleaned_data['plan']:
            tc.add_to_plan(plan=p)
            del p

        # Add components to the case
        for c in form.cleaned_data['component']:
            tc.add_component(component=c)
            del c

        # Add tag to the case
        for tag in TestTag.string_to_list(values.get('tag', [])):
            t, c = TestTag.objects.get_or_create(name=tag)
            tc.add_tag(tag=t)
    else:
        # Print the errors if the form is not passed validation.
        raise ValueError(forms.errors_to_list(form))

    return get(request, tc.case_id)
Ejemplo n.º 39
0
def create(request, values):
    """
    Description: Creates a new Test Case object and stores it in the database.

    Params:      $values - Array/Hash: A reference to a hash or array of hashes with keys and values
                 matching the fields of the test case to be created.
      +----------------------------+----------------+-----------+---------------------------------------+
      | Field                      | Type           | Null      | Description                           |
      +----------------------------+----------------+-----------+---------------------------------------+
      | product                    | Integer        | Required  | ID of Product                         |
      | category                   | Integer        | Required  | ID of Category                        |
      | priority                   | Integer        | Required  | ID of Priority                        |
      | summary                    | String         | Required  |                                       |
      | case_status                | Integer        | Optional  | ID of case status                     |
      | plan                       | Array/Str/Int  | Optional  | ID or List of plan_ids                |
      | component                  | Integer/String | Optional  | ID of Priority                        |
      | default_tester             | String         | Optional  | Login of tester                       |
      | estimated_time             | String         | Optional  | 2h30m30s(recommend) or HH:MM:SS Format|
      | is_automated               | Integer        | Optional  | 0: Manual, 1: Auto, 2: Both           |
      | is_automated_proposed      | Boolean        | Optional  | Default 0                             |
      | script                     | String         | Optional  |                                       |
      | arguments                  | String         | Optional  |                                       |
      | requirement                | String         | Optional  |                                       |
      | alias                      | String         | Optional  | Must be unique                        |
      | action                     | String         | Optional  |                                       |
      | effect                     | String         | Optional  | Expected Result                       |
      | setup                      | String         | Optional  |                                       |
      | breakdown                  | String         | Optional  |                                       |
      | tag                        | Array/String   | Optional  | String Comma separated                |
      | bug                        | Array/String   | Optional  | String Comma separated                |
      | extra_link                 | String         | Optional  | reference link                        |
      +----------------------------+----------------+-----------+---------------------------------------+

    Returns:     Array/Hash: The newly created object hash if a single case was created, or
                             an array of objects if more than one was created. If any single case threw an
                             error during creation, a hash with an ERROR key will be set in its place.

    Example:
    # Minimal test case parameters
    >>> values = {
        'category': 135,
        'product': 61,
        'summary': 'Testing XML-RPC',
        'priority': 1,
    }
    >>> TestCase.create(values)
    """
    from tcms.core import forms
    from tcms.xmlrpc.forms import NewCaseForm

    if not (values.get('category') or values.get('summary')):
        raise ValueError()

    values['component'] = pre_process_ids(values.get('component', []))
    values['plan'] = pre_process_ids(values.get('plan', []))
    values['bug'] = pre_process_ids(values.get('bug', []))
    if values.get('estimated_time'):
        values['estimated_time'] = pre_process_estimated_time(values.get('estimated_time'))

    form = NewCaseForm(values)
    form.populate(values.get('product'))

    if form.is_valid():
        # Create the case
        tc = TestCase.create(author=request.user, values=form.cleaned_data)

        # Add case text to the case
        tc.add_text(
            action=form.cleaned_data['action'] or '',
            effect=form.cleaned_data['effect'] or '',
            setup=form.cleaned_data['setup'] or '',
            breakdown=form.cleaned_data['breakdown'] or '',
        )

        # Add the case to specific plans
        for p in form.cleaned_data['plan']:
            tc.add_to_plan(plan=p)
            del p

        # Add components to the case
        for c in form.cleaned_data['component']:
            tc.add_component(component=c)
            del c

        # Add tag to the case
        for tag in TestTag.string_to_list(values.get('tag', [])):
            t, c = TestTag.objects.get_or_create(name=tag)
            tc.add_tag(tag=t)
    else:
        # Print the errors if the form is not passed validation.
        raise ValueError(forms.errors_to_list(form))

    return get(request, tc.case_id)
Ejemplo n.º 40
0
def update(request, case_ids, values):
    """
    Description: Updates the fields of the selected case or cases.

    Params:      $case_ids - Integer/String/Array
                             Integer: A single TestCase ID.
                             String:  A comma separates string of TestCase IDs for batch
                                      processing.
                             Array:   An array of case IDs for batch mode processing

                 $values   - Hash of keys matching TestCase fields and the new values
                             to set each field to.

    Returns:  Array: an array of case hashes. If the update on any particular
                     case failed, the has will contain a ERROR key and the
                     message as to why it failed.
        +-----------------------+----------------+-----------------------------------------+
        | Field                 | Type           | Null                                    |
        +-----------------------+----------------+-----------------------------------------+
        | case_status           | Integer        | Optional                                |
        | product               | Integer        | Optional(Required if changes category)  |
        | category              | Integer        | Optional                                |
        | priority              | Integer        | Optional                                |
        | default_tester        | String/Integer | Optional(str - user_name, int - user_id)|
        | estimated_time        | String         | Optional(2h30m30s(recommend) or HH:MM:SS|
        | is_automated          | Integer        | Optional(0 - Manual, 1 - Auto, 2 - Both)|
        | is_automated_proposed | Boolean        | Optional                                |
        | script                | String         | Optional                                |
        | arguments             | String         | Optional                                |
        | summary               | String         | Optional                                |
        | requirement           | String         | Optional                                |
        | alias                 | String         | Optional                                |
        | notes                 | String         | Optional                                |
        | extra_link            | String         | Optional(reference link)
        +-----------------------+----------------+-----------------------------------------+

    Example:
    # Update alias to 'tcms' for case 12345 and 23456
    >>> TestCase.update([12345, 23456], {'alias': 'tcms'})
    """
    from tcms.core import forms
    from tcms.xmlrpc.forms import UpdateCaseForm

    if values.get('estimated_time'):
        values['estimated_time'] = pre_process_estimated_time(values.get('estimated_time'))

    form = UpdateCaseForm(values)

    if values.get('category') and not values.get('product'):
        raise ValueError('Product ID is required for category')

    if values.get('product'):
        form.populate(product_id=values['product'])

    if form.is_valid():
        tcs = TestCase.update(
            case_ids=pre_process_ids(value=case_ids),
            values=form.cleaned_data,
        )
    else:
        raise ValueError(forms.errors_to_list(form))

    query = {'pk__in': tcs.values_list('pk', flat=True)}
    return TestCase.to_xmlrpc(query)
Ejemplo n.º 41
0
 def test_get_empty_result(self):
     result = Product.objects.aggregate(max_pk=Max('pk'))
     unknown_pk = result['max_pk'] + 1
     self.assertListEqual([], list(TestCase.list({'product': unknown_pk})))