Search in sources :

Example 36 with TestCase

use of org.cerberus.crud.entity.TestCase in project cerberus-source by cerberustesting.

the class CreateTestCase method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("test"), "");
    String testcase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("testCase"), "");
    String originalTest = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTest"), "");
    String originalTestCase = ParameterParserUtil.parseStringParamAndSanitize(request.getParameter("originalTestCase"), "");
    // Prepare the final answer.
    MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
    Answer finalAnswer = new Answer(msg1);
    /**
     * Checking all constrains before calling the services.
     */
    if (StringUtil.isNullOrEmpty(test) && StringUtil.isNullOrEmpty(testcase)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Case").replace("%OPERATION%", "Create").replace("%REASON%", "mandatory fields (test or testcase) are missing."));
        finalAnswer.setResultMessage(msg);
    } else {
        /**
         * All data seems cleans so we can call the services.
         */
        ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        testCaseService = appContext.getBean(ITestCaseService.class);
        testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
        testCaseLabelFactory = appContext.getBean(IFactoryTestCaseLabel.class);
        testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
        testCaseCountryFactory = appContext.getBean(IFactoryTestCaseCountry.class);
        testCaseCountryPropertiesService = appContext.getBean(ITestCaseCountryPropertiesService.class);
        testCaseStepService = appContext.getBean(ITestCaseStepService.class);
        testCaseStepActionService = appContext.getBean(ITestCaseStepActionService.class);
        testCaseStepActionControlService = appContext.getBean(ITestCaseStepActionControlService.class);
        TestCase testCaseData = getTestCaseFromRequest(request);
        ans = testCaseService.create(testCaseData);
        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
        if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
            /**
             * Object created. Adding Log entry.
             */
            ILogEventService logEventService = appContext.getBean(LogEventService.class);
            logEventService.createForPrivateCalls("/CreateTestCase", "CREATE", "Create TestCase : ['" + testcase + "']", request);
            // Update labels
            if (request.getParameter("labelList") != null) {
                JSONArray objLabelArray = new JSONArray(request.getParameter("labelList"));
                List<TestCaseLabel> labelList = new ArrayList();
                labelList = getLabelListFromRequest(request, appContext, test, testcase, objLabelArray);
                // Update the Database with the new list.
                ans = testCaseLabelService.compareListAndUpdateInsertDeleteElements(test, testcase, labelList);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
            }
            // Update Countries
            if (request.getParameter("countryList") != null) {
                JSONArray objCountryArray = new JSONArray(request.getParameter("countryList"));
                List<TestCaseCountry> tccList = new ArrayList();
                tccList = getCountryListFromRequest(request, appContext, test, testcase, objCountryArray);
                // Update the Database with the new list.
                ans = testCaseCountryService.compareListAndUpdateInsertDeleteElements(test, testcase, tccList);
                finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                // Duplicate other objects.
                List<TestCaseCountryProperties> tccpList = new ArrayList();
                List<TestCaseCountryProperties> newTccpList = new ArrayList();
                if (!tccList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    tccpList = testCaseCountryPropertiesService.findListOfPropertyPerTestTestCase(originalTest, originalTestCase);
                    // Build a new list with the countries that exist for the testcase.
                    for (TestCaseCountryProperties curTccp : tccpList) {
                        if (testCaseCountryService.exist(test, testcase, curTccp.getCountry())) {
                            newTccpList.add(curTccp);
                        }
                    }
                    if (!newTccpList.isEmpty()) {
                        ans = testCaseCountryPropertiesService.duplicateList(newTccpList, test, testcase);
                        finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                    }
                }
            }
            List<TestCaseStep> tcsList = new ArrayList();
            if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                tcsList = testCaseStepService.getListOfSteps(originalTest, originalTestCase);
                if (!tcsList.isEmpty()) {
                    ans = testCaseStepService.duplicateList(tcsList, test, testcase);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
            List<TestCaseStepAction> tcsaList = new ArrayList();
            if (!tcsList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                tcsaList = testCaseStepActionService.findTestCaseStepActionbyTestTestCase(originalTest, originalTestCase);
                if (!tcsaList.isEmpty()) {
                    ans = testCaseStepActionService.duplicateList(tcsaList, test, testcase);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
            if (!tcsList.isEmpty() && !tcsaList.isEmpty() && ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                List<TestCaseStepActionControl> tcsacList = testCaseStepActionControlService.findControlByTestTestCase(originalTest, originalTestCase);
                if (!tcsacList.isEmpty()) {
                    ans = testCaseStepActionControlService.duplicateList(tcsacList, test, testcase);
                    finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : ITestCaseStepActionService(org.cerberus.crud.service.ITestCaseStepActionService) TestCaseStepAction(org.cerberus.crud.entity.TestCaseStepAction) TestCaseCountryProperties(org.cerberus.crud.entity.TestCaseCountryProperties) PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) TestCaseStep(org.cerberus.crud.entity.TestCaseStep) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService) ApplicationContext(org.springframework.context.ApplicationContext) ITestCaseCountryPropertiesService(org.cerberus.crud.service.ITestCaseCountryPropertiesService) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) TestCaseStepActionControl(org.cerberus.crud.entity.TestCaseStepActionControl) ITestCaseLabelService(org.cerberus.crud.service.ITestCaseLabelService) ITestCaseStepService(org.cerberus.crud.service.ITestCaseStepService) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) JSONArray(org.json.JSONArray) IFactoryTestCaseCountry(org.cerberus.crud.factory.IFactoryTestCaseCountry) ITestCaseStepActionControlService(org.cerberus.crud.service.ITestCaseStepActionControlService) Answer(org.cerberus.util.answer.Answer) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel)

Example 37 with TestCase

use of org.cerberus.crud.entity.TestCase in project cerberus-source by cerberustesting.

the class CreateTestCase method getTestCaseFromRequest.

// </editor-fold>
private TestCase getTestCaseFromRequest(HttpServletRequest request) throws CerberusException, JSONException {
    TestCase tc = new TestCase();
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    // Parameter that needs to be secured --> We SECURE+DECODE them
    tc.setImplementer(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("implementer"), "", charset));
    tc.setUsrCreated(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getUserPrincipal().getName(), "", charset));
    tc.setUsrModif(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getUserPrincipal().getName(), "", charset));
    if (StringUtils.isEmpty(request.getParameter("project"))) {
        tc.setProject(null);
    } else {
        tc.setProject(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("project"), "", charset));
    }
    tc.setApplication(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), "", charset));
    tc.setActiveQA(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("activeQA"), "", charset));
    tc.setActiveUAT(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("activeUAT"), "", charset));
    tc.setActivePROD(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("activeProd"), "", charset));
    tc.setFromBuild(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("fromSprint"), "", charset));
    tc.setFromRev(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("fromRev"), "", charset));
    tc.setToBuild(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("toSprint"), "", charset));
    tc.setToRev(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("toRev"), "", charset));
    tc.setTcActive(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("active"), "", charset));
    tc.setTargetBuild(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("targetSprint"), "", charset));
    tc.setTargetRev(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("targetRev"), "", charset));
    tc.setPriority(ParameterParserUtil.parseIntegerParamAndDecode(request.getParameter("priority"), 0, charset));
    tc.setTest(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "", charset));
    tc.setTestCase(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), "", charset));
    tc.setTicket(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("ticket"), "", charset));
    tc.setOrigine(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("origin"), "", charset));
    tc.setRefOrigine(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("refOrigin"), "", charset));
    tc.setGroup(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("group"), "", charset));
    tc.setStatus(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("status"), "", charset));
    tc.setDescription(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("shortDesc"), "", charset));
    tc.setBugID(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("bugId"), "", charset));
    tc.setComment(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("comment"), "", charset));
    tc.setFunction(ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("function"), "", charset));
    tc.setTestCaseVersion(0);
    // Parameter that we cannot secure as we need the html --> We DECODE them
    tc.setHowTo(ParameterParserUtil.parseStringParamAndDecode(request.getParameter("howTo"), "", charset));
    tc.setBehaviorOrValueExpected(ParameterParserUtil.parseStringParamAndDecode(request.getParameter("behaviorOrValueExpected"), "", charset));
    return tc;
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) TestCase(org.cerberus.crud.entity.TestCase)

Example 38 with TestCase

use of org.cerberus.crud.entity.TestCase in project cerberus-source by cerberustesting.

the class CreateTestCaseLabel method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    // Parameter that are already controled by GUI (no need to decode) --> We SECURE them
    // Parameter that needs to be secured --> We SECURE+DECODE them
    // Parameter that we cannot secure as we need the html --> We DECODE them
    Integer myIdInt = 0;
    String[] myLabelIdList = request.getParameterValues("labelid");
    String[] myTestList = request.getParameterValues("test");
    String[] myTestCaseList = request.getParameterValues("testcase");
    if ((myTestList.length == 0) || (myTestCaseList.length == 0) || (myLabelIdList.length == 0)) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Missing Parameter (either test, testcase or labelid)."));
        ans.setResultMessage(msg);
    } else if (myTestList.length != myTestCaseList.length) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Number of Test does not match number of testcase."));
        ans.setResultMessage(msg);
    }
    StringBuilder output_message = new StringBuilder();
    int massErrorCounter = 0;
    for (int i = 0; i < myLabelIdList.length; i++) {
        String myLabelId = myLabelIdList[i];
        myIdInt = 0;
        boolean label_error = true;
        try {
            if (myLabelId != null && !myLabelId.equals("")) {
                myIdInt = Integer.valueOf(policy.sanitize(myLabelId));
                label_error = false;
            }
        } catch (Exception ex) {
            label_error = true;
        }
        /**
         * Checking all constrains before calling the services.
         */
        if (label_error) {
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Update").replace("%REASON%", "Could not manage to convert labelid to an integer value or labelid is missing."));
            ans.setResultMessage(msg);
            massErrorCounter++;
            output_message.append("<br>id : ").append(myLabelId).append(" - ").append(msg.getDescription());
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ILabelService labelService = appContext.getBean(ILabelService.class);
            IFactoryTestCaseLabel factoryTestCaseLabel = appContext.getBean(IFactoryTestCaseLabel.class);
            ITestCaseLabelService testCaseLabelService = appContext.getBean(ITestCaseLabelService.class);
            ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
            IApplicationService applicationService = appContext.getBean(IApplicationService.class);
            AnswerItem resp = labelService.readByKey(myIdInt);
            if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                /**
                 * Object could not be found. We stop here and report the
                 * error.
                 */
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Label does not exist."));
                ans.setResultMessage(msg);
                massErrorCounter++;
                output_message.append("<br>labelid : ").append(myLabelId).append(" - ").append(msg.getDescription());
            } else {
                Label myLab = (Label) resp.getItem();
                for (int j = 0; j < myTestList.length; j++) {
                    String myTest = myTestList[j];
                    String myTestCase = myTestCaseList[j];
                    resp = testCaseService.readByKey(myTest, myTestCase);
                    if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                        /**
                         * Object could not be found. We stop here and
                         * report the error.
                         */
                        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                        msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Create").replace("%REASON%", "Test Case does not exist."));
                        ans.setResultMessage(msg);
                        massErrorCounter++;
                        output_message.append("<br>testcase : ").append(myLabelId).append(" - ").append(msg.getDescription());
                    } else {
                        TestCase myTestCaseObj = (TestCase) resp.getItem();
                        resp = applicationService.readByKey(myTestCaseObj.getApplication());
                        if ((resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                            Application myApplication = (Application) resp.getItem();
                            if ((StringUtil.isNullOrEmpty(myLab.getSystem())) || (myApplication.getSystem().equals(myLab.getSystem()))) {
                                TestCaseLabel tcLabel = factoryTestCaseLabel.create(0, myTest, myTestCase, myIdInt, request.getRemoteUser(), null, "", null, null);
                                ans = testCaseLabelService.create(tcLabel);
                                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                                    /**
                                     * Update was successful. Adding Log
                                     * entry.
                                     */
                                    logEventService.createForPrivateCalls("/CreateTestCaseLabel", "CREATE", "Created TestCaseLabel : ['" + myIdInt + "'|'" + myTest + "'|'" + myTestCase + "']", request);
                                } else {
                                    massErrorCounter++;
                                    output_message.append("<br>Label : ").append(myLabelId).append(" Test : '").append(myTest).append("' TestCase : '").append(myTestCase).append("' - ").append(ans.getResultMessage().getDescription());
                                }
                            } else {
                                massErrorCounter++;
                                output_message.append("<br>Label : ").append(myLabelId).append(" Test : '").append(myTest).append("' TestCase : '").append(myTestCase).append("' - ").append("Label does not belong to the same system as TestCase system.");
                            }
                        }
                    }
                }
            }
        }
    }
    if (myTestList.length > 1) {
        if (massErrorCounter == myTestList.length) {
            // All updates are in ERROR.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update").replace("%REASON%", massErrorCounter + " label links(s) out of " + (myTestList.length * myLabelIdList.length) + " failed to be created due to an issue.<br>") + output_message.toString());
            ans.setResultMessage(msg);
        } else if (massErrorCounter > 0) {
            // At least 1 update in error
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update").replace("%REASON%", massErrorCounter + " label links(s) out of " + (myTestList.length * myLabelIdList.length) + " failed to be created due to an issue.<br>") + output_message.toString());
            ans.setResultMessage(msg);
        } else {
            // No error detected.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
            msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "Mass Update") + "\n\nAll " + (myTestList.length * myLabelIdList.length) + " label links(s) created successfuly.");
            ans.setResultMessage(msg);
        }
        logEventService.createForPrivateCalls("/CreateTestCaseLabel", "MASSUPDATE", msg.getDescription(), request);
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse);
    response.getWriter().flush();
}
Also used : PolicyFactory(org.owasp.html.PolicyFactory) MessageEvent(org.cerberus.engine.entity.MessageEvent) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) TestCaseLabel(org.cerberus.crud.entity.TestCaseLabel) Label(org.cerberus.crud.entity.Label) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) AnswerItem(org.cerberus.util.answer.AnswerItem) ServletException(javax.servlet.ServletException) JSONException(org.json.JSONException) IOException(java.io.IOException) CerberusException(org.cerberus.exception.CerberusException) ILabelService(org.cerberus.crud.service.ILabelService) Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) ITestCaseService(org.cerberus.crud.service.ITestCaseService) ILogEventService(org.cerberus.crud.service.ILogEventService) Application(org.cerberus.crud.entity.Application) IFactoryTestCaseLabel(org.cerberus.crud.factory.IFactoryTestCaseLabel) ITestCaseLabelService(org.cerberus.crud.service.ITestCaseLabelService) IApplicationService(org.cerberus.crud.service.IApplicationService)

Example 39 with TestCase

use of org.cerberus.crud.entity.TestCase in project cerberus-source by cerberustesting.

the class DeleteTestCaseCountry method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
    JSONObject jsonResponse = new JSONObject();
    Answer ans = new Answer();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
    msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
    ans.setResultMessage(msg);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
    String charset = request.getCharacterEncoding();
    response.setContentType("application/json");
    // Calling Servlet Transversal Util.
    ServletUtil.servletStart(request);
    /**
     * Parsing and securing all required parameters.
     */
    String test = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("test"), "", charset);
    String testcase = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("testCase"), null, charset);
    String country = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("country"), "", charset);
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    /**
     * Checking all constrains before calling the services.
     */
    if (testcase == null || (StringUtil.isNullOrEmpty(test)) || (StringUtil.isNullOrEmpty(country))) {
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
        msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Delete").replace("%REASON%", "test or testCase or country is missing!"));
        ans.setResultMessage(msg);
    } else {
        // Checking the autorities here.
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
        AnswerItem resp = testCaseService.readByKey(test, testcase);
        TestCase tc = (TestCase) resp.getItem();
        if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
            /**
             * Object could not be found. We stop here and report the error.
             */
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "TestCase does not exist."));
            ans.setResultMessage(msg);
        } else if (!request.isUserInRole("Test")) {
            // We cannot update the testcase if the user is not at least in Test role.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "Not enought privilege to create the testCaseCountry. You must belong to Test Privilege."));
            ans.setResultMessage(msg);
        } else if ((tc.getStatus().equalsIgnoreCase("WORKING")) && !(request.isUserInRole("TestAdmin"))) {
            // If Test Case is WORKING we need TestAdmin priviliges.
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
            msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Create").replace("%REASON%", "Not enought privilege to create the testCaseCountry. The test case is in WORKING status and needs TestAdmin privilege to be updated"));
            ans.setResultMessage(msg);
        } else {
            /**
             * All data seems cleans so we can call the services.
             */
            ITestCaseCountryService testCaseCountryService = appContext.getBean(ITestCaseCountryService.class);
            resp = testCaseCountryService.readByKey(test, testcase, country);
            if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
                /**
                 * Object could not be found. We stop here and report the
                 * error.
                 */
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
                msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseCountry").replace("%OPERATION%", "Delete").replace("%REASON%", "TestCaseCountry does not exist."));
                ans.setResultMessage(msg);
            } else {
                /**
                 * The service was able to perform the query and confirm the
                 * object exist, then we can delete it.
                 */
                TestCaseCountry testCaseCountryData = (TestCaseCountry) resp.getItem();
                ans = testCaseCountryService.delete(testCaseCountryData);
                if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
                    /**
                     * Delete was successful. Adding Log entry.
                     */
                    ILogEventService logEventService = appContext.getBean(LogEventService.class);
                    logEventService.createForPrivateCalls("/DeleteTestCaseCountry", "DELETE", "Delete TestCaseCountry : ['" + test + "'|'" + testcase + "'|'" + country + "']", request);
                }
            }
        }
    }
    /**
     * Formating and returning the json result.
     */
    jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
    jsonResponse.put("message", ans.getResultMessage().getDescription());
    response.getWriter().print(jsonResponse.toString());
    response.getWriter().flush();
}
Also used : Answer(org.cerberus.util.answer.Answer) ApplicationContext(org.springframework.context.ApplicationContext) JSONObject(org.json.JSONObject) PolicyFactory(org.owasp.html.PolicyFactory) TestCase(org.cerberus.crud.entity.TestCase) MessageEvent(org.cerberus.engine.entity.MessageEvent) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseCountry(org.cerberus.crud.entity.TestCaseCountry) ILogEventService(org.cerberus.crud.service.ILogEventService) AnswerItem(org.cerberus.util.answer.AnswerItem) ITestCaseCountryService(org.cerberus.crud.service.ITestCaseCountryService)

Example 40 with TestCase

use of org.cerberus.crud.entity.TestCase in project cerberus-source by cerberustesting.

the class GetExecutionQueue method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws org.json.JSONException
 * @throws org.cerberus.exception.CerberusException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException, CerberusException {
    AnswerItem answer = new AnswerItem(new MessageEvent(MessageEventEnum.DATA_OPERATION_OK));
    JSONObject jsonResponse = new JSONObject();
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    boolean check = ParameterParserUtil.parseBooleanParam(request.getParameter("check"), false);
    boolean push = ParameterParserUtil.parseBooleanParam(request.getParameter("push"), false);
    if (check) {
        IApplicationService applicationService = appContext.getBean(IApplicationService.class);
        IInvariantService invariantService = appContext.getBean(IInvariantService.class);
        ITestService testService = appContext.getBean(ITestService.class);
        ITestCaseService testCaseService = appContext.getBean(ITestCaseService.class);
        ICountryEnvParamService cepService = appContext.getBean(ICountryEnvParamService.class);
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        testCaseExecutionService = appContext.getBean(ITestCaseExecutionService.class);
        List<ExecutionValidator> inQueue = new ArrayList<>();
        JSONArray testCaseList = new JSONArray(request.getParameter("testcase"));
        JSONArray environmentList = new JSONArray(request.getParameter("environment"));
        JSONArray countryList = new JSONArray(request.getParameter("countries"));
        /**
         * Creating all the list from the JSON to call the services
         */
        List<TestCase> TCList = new ArrayList<>();
        List<String> envList = new ArrayList<>();
        List<String> countries = new ArrayList<>();
        for (int index = 0; index < testCaseList.length(); index++) {
            JSONObject testCaseJson = testCaseList.getJSONObject(index);
            TestCase tc = new TestCase();
            tc.setTest(testCaseJson.getString("test"));
            tc.setTestCase(testCaseJson.getString("testcase"));
            TCList.add(tc);
        }
        for (int index = 0; index < environmentList.length(); index++) {
            String environment = environmentList.getString(index);
            envList.add(environment);
        }
        for (int index = 0; index < countryList.length(); index++) {
            String country = countryList.getString(index);
            countries.add(country);
        }
        List<TestCaseExecution> tceList = testCaseExecutionService.createAllTestCaseExecution(TCList, envList, countries);
        IExecutionCheckService execCheckService = appContext.getBean(IExecutionCheckService.class);
        for (TestCaseExecution execution : tceList) {
            boolean exception = false;
            ExecutionValidator validator = new ExecutionValidator();
            try {
                execution.setTestObj(testService.convert(testService.readByKey(execution.getTest())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_TEST_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%TEST%", execution.getTest()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setTestCaseObj(testCaseService.findTestCaseByKey(execution.getTest(), execution.getTestCase()));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_TESTCASE_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%TEST%", execution.getTest()));
                mes.setDescription(mes.getDescription().replace("%TESTCASE%", execution.getTestCase()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setApplicationObj(applicationService.convert(applicationService.readByKey(execution.getTestCaseObj().getApplication())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_APPLICATION_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%APPLI%", execution.getTestCaseObj().getApplication()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            execution.setEnvironmentData(execution.getEnvironment());
            try {
                execution.setCountryEnvParam(cepService.convert(cepService.readByKey(execution.getApplicationObj().getSystem(), execution.getCountry(), execution.getEnvironment())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_COUNTRYENV_NOT_FOUND);
                mes.setDescription(mes.getDescription().replace("%SYSTEM%", execution.getApplicationObj().getSystem()));
                mes.setDescription(mes.getDescription().replace("%COUNTRY%", execution.getCountry()));
                mes.setDescription(mes.getDescription().replace("%ENV%", execution.getEnvironmentData()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            try {
                execution.setEnvironmentDataObj(invariantService.convert(invariantService.readByKey("ENVIRONMENT", execution.getEnvironmentData())));
            } catch (CerberusException ex) {
                MessageGeneral mes = new MessageGeneral(MessageGeneralEnum.VALIDATION_FAILED_ENVIRONMENT_DOESNOTEXIST);
                mes.setDescription(mes.getDescription().replace("%ENV%", execution.getEnvironmentData()));
                validator.setValid(false);
                validator.setMessage(mes.getDescription());
                exception = true;
            }
            String browser = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_BROWSER), DEFAULT_VALUE_BROWSER);
            if (!(StringUtil.isNullOrEmpty(browser))) {
                // if application is not GUI, we force browser to empty value.
                if (execution.getApplicationObj() != null && execution.getApplicationObj().getType() != null && !(execution.getApplicationObj().getType().equalsIgnoreCase(Application.TYPE_GUI))) {
                    execution.setBrowser("");
                }
            } else {
                execution.setBrowser(browser);
            }
            String manualExecution = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION);
            execution.setManualExecution(manualExecution);
            if (exception == false) {
                /**
                 * Checking the execution as it would be checked in the
                 * engine
                 */
                MessageGeneral message = execCheckService.checkTestCaseExecution(execution);
                if (!(message.equals(new MessageGeneral(MessageGeneralEnum.EXECUTION_PE_CHECKINGPARAMETERS)))) {
                    validator.setValid(false);
                    validator.setMessage(message.getDescription());
                } else {
                    validator.setValid(true);
                    validator.setMessage("Valid Execution.");
                }
            }
            validator.setExecution(execution);
            inQueue.add(validator);
        }
        JSONArray dataArray = new JSONArray();
        for (ExecutionValidator tce : inQueue) {
            JSONObject exec = new JSONObject();
            exec.put("test", tce.getExecution().getTest());
            exec.put("testcase", tce.getExecution().getTestCase());
            exec.put("env", tce.getExecution().getEnvironment());
            exec.put("country", tce.getExecution().getCountry());
            exec.put("appType", tce.getExecution().getApplicationObj().getType());
            exec.put("isValid", tce.isValid());
            exec.put("message", tce.getMessage());
            dataArray.put(exec);
        }
        jsonResponse.put("contentTable", dataArray);
    }
    if (push) {
        IExecutionThreadPoolService executionThreadService = appContext.getBean(IExecutionThreadPoolService.class);
        IParameterService parameterService = appContext.getBean(IParameterService.class);
        IFactoryTestCaseExecutionQueue inQueueFactoryService = appContext.getBean(IFactoryTestCaseExecutionQueue.class);
        ITestCaseExecutionQueueService inQueueService = appContext.getBean(ITestCaseExecutionQueueService.class);
        int addedToQueue = 0;
        JSONArray toAddList = new JSONArray(request.getParameter("toAddList"));
        JSONArray browsers = new JSONArray(request.getParameter("browsers"));
        Date requestDate = new Date();
        /**
         * RETRIEVING ROBOT SETTINGS *
         */
        String robot = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT), null);
        String robotIP = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT_IP), null);
        String robotPort = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_ROBOT_PORT), null);
        String browserVersion = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_BROWSER_VERSION), null);
        String platform = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_PLATFORM), null);
        String screenSize = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_SCREENSIZE), null);
        /**
         * RETRIEVING EXECUTION SETTINGS *
         */
        String tag = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_TAG), "");
        int screenshot = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_SCREENSHOT), DEFAULT_VALUE_SCREENSHOT);
        int verbose = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_VERBOSE), DEFAULT_VALUE_VERBOSE);
        String timeout = request.getParameter(PARAMETER_TIMEOUT);
        int pageSource = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_PAGE_SOURCE), DEFAULT_VALUE_PAGE_SOURCE);
        int seleniumLog = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_SELENIUM_LOG), DEFAULT_VALUE_SELENIUM_LOG);
        int retries = ParameterParserUtil.parseIntegerParam(request.getParameter(PARAMETER_RETRIES), DEFAULT_VALUE_RETRIES);
        String manualExecution = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_EXECUTION), DEFAULT_VALUE_MANUAL_EXECUTION);
        /**
         * RETRIEVING MANUAL ENVIRONMENT SETTINGS *
         */
        String manualHost = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_HOST), null);
        String manualContextRoot = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_CONTEXT_ROOT), null);
        String manualLoginRelativeURL = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_LOGIN_RELATIVE_URL), null);
        String manualEnvData = ParameterParserUtil.parseStringParam(request.getParameter(PARAMETER_MANUAL_ENV_DATA), null);
        // Create Tag when exist.
        if (!StringUtil.isNullOrEmpty(tag)) {
            // We create or update it.
            ITagService tagService = appContext.getBean(ITagService.class);
            tagService.createAuto(tag, "", request.getRemoteUser());
        }
        for (int index = 0; index < toAddList.length(); index++) {
            JSONObject toAdd = toAddList.getJSONObject(index);
            int manualURL = 0;
            if (toAdd.getString("env").equals("MANUAL")) {
                manualURL = 1;
            }
            try {
                // Create the template
                TestCaseExecutionQueue tceiq = inQueueFactoryService.create(toAdd.getString("test"), toAdd.getString("testcase"), toAdd.getString("country"), toAdd.getString("env"), robot, robotIP, robotPort, "", browserVersion, platform, screenSize, manualURL, manualHost, manualContextRoot, manualLoginRelativeURL, manualEnvData, tag, screenshot, verbose, timeout, pageSource, seleniumLog, 0, retries, manualExecution, 1000, request.getRemoteUser(), null, null, null);
                // Then fill it with either no browser
                if ((browsers.length() == 0) || ((toAdd.getString("appType") != null) && (!toAdd.getString("appType").equalsIgnoreCase(Application.TYPE_GUI)))) {
                    inQueueService.convert(inQueueService.create(tceiq));
                    addedToQueue++;
                } else // Or with required browsers
                {
                    for (int iterBrowser = 0; iterBrowser < browsers.length(); iterBrowser++) {
                        tceiq.setBrowser(browsers.getString(iterBrowser));
                        try {
                            inQueueService.convert(inQueueService.create(tceiq));
                            addedToQueue++;
                        } catch (CerberusException e) {
                            LOG.warn("Unable to insert execution in queue " + tceiq, e);
                        }
                    }
                }
            } catch (FactoryCreationException e) {
                LOG.warn("Unable to create the execution queue template", e);
            }
        }
        // Trigger execution if necessary
        if (addedToQueue > 0) {
            try {
                executionThreadService.executeNextInQueueAsynchroneously(false);
            } catch (CerberusException ex) {
                String errorMessage = "Unable to feed the execution queue due to " + ex.getMessage();
                LOG.warn(errorMessage);
                answer.setResultMessage(new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED));
                answer.getResultMessage().setDescription(errorMessage);
            }
            jsonResponse.put("messageType", answer.getResultMessage().getMessage().getCodeString());
            jsonResponse.put("message", answer.getResultMessage().getDescription());
            jsonResponse.put("addedToQueue", addedToQueue);
            jsonResponse.put("redirect", "ReportingExecutionByTag.jsp?Tag=" + StringUtil.encodeAsJavaScriptURIComponent(tag));
        }
    }
    response.setContentType("application/json");
    response.getWriter().print(jsonResponse.toString());
}
Also used : IExecutionCheckService(org.cerberus.engine.execution.IExecutionCheckService) MessageEvent(org.cerberus.engine.entity.MessageEvent) ArrayList(java.util.ArrayList) IParameterService(org.cerberus.crud.service.IParameterService) ITestCaseExecutionService(org.cerberus.crud.service.ITestCaseExecutionService) ExecutionValidator(org.cerberus.dto.ExecutionValidator) FactoryCreationException(org.cerberus.exception.FactoryCreationException) ApplicationContext(org.springframework.context.ApplicationContext) MessageGeneral(org.cerberus.engine.entity.MessageGeneral) ITestService(org.cerberus.crud.service.ITestService) ITestCaseService(org.cerberus.crud.service.ITestCaseService) TestCaseExecutionQueue(org.cerberus.crud.entity.TestCaseExecutionQueue) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) IApplicationService(org.cerberus.crud.service.IApplicationService) ITestCaseExecutionQueueService(org.cerberus.crud.service.ITestCaseExecutionQueueService) TestCaseExecution(org.cerberus.crud.entity.TestCaseExecution) CerberusException(org.cerberus.exception.CerberusException) IInvariantService(org.cerberus.crud.service.IInvariantService) JSONArray(org.json.JSONArray) AnswerItem(org.cerberus.util.answer.AnswerItem) IFactoryTestCaseExecutionQueue(org.cerberus.crud.factory.IFactoryTestCaseExecutionQueue) Date(java.util.Date) JSONObject(org.json.JSONObject) TestCase(org.cerberus.crud.entity.TestCase) IExecutionThreadPoolService(org.cerberus.engine.threadpool.IExecutionThreadPoolService) ITagService(org.cerberus.crud.service.ITagService) ICountryEnvParamService(org.cerberus.crud.service.ICountryEnvParamService)

Aggregations

TestCase (org.cerberus.crud.entity.TestCase)68 ITestCaseService (org.cerberus.crud.service.ITestCaseService)30 ArrayList (java.util.ArrayList)29 IFactoryTestCase (org.cerberus.crud.factory.IFactoryTestCase)29 JSONObject (org.json.JSONObject)26 AnswerItem (org.cerberus.util.answer.AnswerItem)24 ApplicationContext (org.springframework.context.ApplicationContext)24 MessageEvent (org.cerberus.engine.entity.MessageEvent)23 SQLException (java.sql.SQLException)17 TestCaseCountry (org.cerberus.crud.entity.TestCaseCountry)17 JSONArray (org.json.JSONArray)17 PolicyFactory (org.owasp.html.PolicyFactory)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16 ResultSet (java.sql.ResultSet)16 CerberusException (org.cerberus.exception.CerberusException)16 TestCaseStep (org.cerberus.crud.entity.TestCaseStep)15 ILogEventService (org.cerberus.crud.service.ILogEventService)15 AnswerList (org.cerberus.util.answer.AnswerList)15 List (java.util.List)13