├── .github └── workflows │ └── maven.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── readme-img ├── installingLibsViaMvn.png ├── stf_architecture.png └── stf_logo.png ├── stf-desktop-automation-lib ├── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── jeansantos38 │ │ │ └── stf │ │ │ ├── contants │ │ │ └── ui │ │ │ │ └── LogMessages.java │ │ │ ├── data │ │ │ └── classes │ │ │ │ └── ui │ │ │ │ ├── Details.java │ │ │ │ ├── Element.java │ │ │ │ ├── Navigator.java │ │ │ │ └── NavigatorArea.java │ │ │ ├── enums │ │ │ ├── UiAction.java │ │ │ ├── UiControls.java │ │ │ └── UiMouseButton.java │ │ │ └── framework │ │ │ └── ui │ │ │ ├── DesktopAutomationHelper.java │ │ │ ├── UiAutomationDriver.java │ │ │ ├── UiAutomationHelper.java │ │ │ ├── UiAutomationUtils.java │ │ │ ├── UiElement.java │ │ │ └── UiVisualFeedback.java │ └── test │ │ ├── java │ │ └── system │ │ │ ├── base │ │ │ ├── MainTestBase.java │ │ │ └── UiAutomationTestBase.java │ │ │ └── test │ │ │ ├── UiAutomationBasic.java │ │ │ ├── UiAutomationControls.java │ │ │ ├── UiAutomationGeneric.java │ │ │ └── UiAutomationVisibility.java │ │ └── resources │ │ ├── bin │ │ └── SmartTestFrameworkDemo.exe │ │ ├── imgrDatadriven │ │ └── desktop-apps │ │ │ └── winformSTFdemo │ │ │ └── 1.0 │ │ │ ├── dd_winformSTFdemo_v1-0_SETS_AND_ASSERTS.json │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_false.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_true.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx1.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx2.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_ddl_item2.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_rbt2.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_tbr_value2.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb1.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb2.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_item3_inList.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_false.png │ │ │ ├── mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_true.png │ │ │ ├── reg_checkBox1_default.png │ │ │ └── topBar.png │ │ ├── masters │ │ └── winApp │ │ │ ├── _navigator_STF_Win_Demo-App.yml │ │ │ ├── checkbox_false.png │ │ │ ├── checkbox_true.png │ │ │ ├── notExistentPattern.png │ │ │ ├── radiobutton_false.png │ │ │ ├── radiobutton_true.png │ │ │ ├── stf_ico.png │ │ │ └── trackbarPointer.png │ │ └── scripts │ │ ├── vBoxShutdownVmRestoreSnapshot.bat │ │ └── vBoxStartVmSnapshot.bat └── testRunConfig │ ├── testRunConfig_ui-auto-local.xml │ └── testRunConfig_ui-auto-remote.xml ├── stf-http-client-lib ├── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── jeansantos38 │ │ │ └── stf │ │ │ ├── dataclasses │ │ │ └── web │ │ │ │ ├── http │ │ │ │ ├── HttpDetailedHeader.java │ │ │ │ ├── HttpDetailedHeaders.java │ │ │ │ ├── HttpDetailedRequest.java │ │ │ │ ├── HttpDetailedResponse.java │ │ │ │ └── HttpInternalResponse.java │ │ │ │ └── proxy │ │ │ │ └── ProxySettings.java │ │ │ ├── enums │ │ │ └── http │ │ │ │ ├── HttpRequestLogLevel.java │ │ │ │ ├── HttpRequestMethod.java │ │ │ │ └── StatusCodeVerifierStrategy.java │ │ │ └── framework │ │ │ └── httpclient │ │ │ ├── HttpClient.java │ │ │ ├── HttpContentHandler.java │ │ │ ├── HttpDeleteWithBody.java │ │ │ ├── RequestsLogger.java │ │ │ └── StatusCodeVerifier.java │ └── test │ │ ├── java │ │ └── system │ │ │ └── test │ │ │ ├── base │ │ │ ├── HttpClientTestBase.java │ │ │ ├── MainTestBase.java │ │ │ └── WireMockTestBase.java │ │ │ ├── pojo │ │ │ ├── Bicycle.java │ │ │ ├── Book.java │ │ │ ├── BooksStore.java │ │ │ ├── CommonPayloadBody.java │ │ │ └── Store.java │ │ │ └── rest │ │ │ ├── BuiltInAssertionsTests.java │ │ │ ├── DemoParallelTests.java │ │ │ ├── DeserializeResponseTests.java │ │ │ ├── HeadersTests.java │ │ │ ├── HttpDetailedRequestTests.java │ │ │ ├── HttpLoggerTests.java │ │ │ ├── HttpStatusCodeVerifierTests.java │ │ │ ├── LegacyRequestsTests.java │ │ │ └── ResponseParsingTests.java │ │ └── resources │ │ ├── requestBody.json │ │ ├── responseBody.json │ │ └── responseBooksStore.json └── testRunConfig │ ├── testRunConfig_http-client_rest_demo-tests.xml │ ├── testRunConfig_http-client_thread-mlt_tests.xml │ └── testRunConfig_http-client_thread-single_tests.xml ├── stf-misc-lib ├── pom.xml ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── jeansantos38 │ │ │ └── stf │ │ │ ├── dataclasses │ │ │ └── datadriven │ │ │ │ ├── DataDriven.java │ │ │ │ ├── SmartDataDriven.java │ │ │ │ ├── Statement.java │ │ │ │ └── Statements.java │ │ │ ├── enums │ │ │ ├── serialization │ │ │ │ └── SerializationType.java │ │ │ └── wait │ │ │ │ └── ThreadWait.java │ │ │ └── framework │ │ │ ├── io │ │ │ └── InputOutputHelper.java │ │ │ ├── logger │ │ │ └── TestLog.java │ │ │ ├── misc │ │ │ ├── CalendarHelper.java │ │ │ ├── RandomValuesHelper.java │ │ │ ├── StringsHelper.java │ │ │ └── VisualWarningsHelper.java │ │ │ ├── network │ │ │ └── NetworkHelper.java │ │ │ ├── regex │ │ │ └── RegexHelper.java │ │ │ ├── serialization │ │ │ ├── DeserializeHelper.java │ │ │ ├── JsonParserHelper.java │ │ │ └── SerializeHelper.java │ │ │ └── wait │ │ │ └── WaitHelper.java │ └── test │ │ ├── java │ │ └── system │ │ │ ├── base │ │ │ └── MainTestBase.java │ │ │ ├── pojo │ │ │ ├── Bicycle.java │ │ │ ├── Book.java │ │ │ ├── BooksStore.java │ │ │ ├── Note.java │ │ │ ├── NoteDemoClass.java │ │ │ └── Store.java │ │ │ └── test │ │ │ ├── CalendarTests.java │ │ │ ├── InputOutputTests.java │ │ │ ├── NetworkInterfaceTests.java │ │ │ ├── RegexTests.java │ │ │ └── SerializeDeserializeTests.java │ │ └── resources │ │ ├── booksStore.json │ │ ├── content.json │ │ ├── content.xml │ │ └── content.yml └── testRunConfig │ └── testRunConfig_misc-tests.xml └── stf-webdriver-lib ├── pom.xml ├── src ├── main │ └── java │ │ └── com │ │ └── github │ │ └── jeansantos38 │ │ └── stf │ │ ├── enums │ │ └── webdriver │ │ │ ├── SelectorType.java │ │ │ └── WebDriverAction.java │ │ └── framework │ │ ├── datadriven │ │ ├── AssertWebDriverInstructionSet.java │ │ ├── SetWebDriverInstructionSet.java │ │ ├── WebDriverDataDrivenCommon.java │ │ └── WebDriverDataDrivenHelper.java │ │ └── webdriver │ │ ├── WebDriverAppiumHelper.java │ │ ├── WebDriverCommonHelper.java │ │ └── WebDriverSeleniumHelper.java └── test │ ├── java │ └── system │ │ └── test │ │ ├── base │ │ ├── MainTestBase.java │ │ ├── WebUiTestBase.java │ │ └── WireMockTestBase.java │ │ └── ui │ │ └── WebUiTests.java │ └── resources │ ├── __files │ ├── stf_demo_form.html │ └── table.html │ └── webUiDatadriven │ └── dataDriven_webcontent.json └── testRunConfig └── testRunConfig_webcontent_ui_demo-tests.xml /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 1.11 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.11 23 | - name: Build with Maven 24 | run: mvn clean install -DskipTests --file pom.xml 25 | - name: Run General Helpers tests 26 | run: mvn test --file stf-misc-lib/pom.xml -DnetworkInterface="eth0" 27 | - name: Run Http-Client tests 28 | run: mvn test --file stf-http-client-lib/pom.xml 29 | 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # git ls-files --others --exclude-from=.git/info/exclude 2 | # Lines that start with '#' are comments. 3 | # For a project mostly in C, the following would be a good set of 4 | # exclude patterns (uncomment them if you want to use them): 5 | # *.[oa] 6 | # *~ 7 | */target/* 8 | */.idea/* 9 | /.idea/* 10 | */allure-results/* 11 | *.iml 12 | */test-output/* 13 | *.db -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 HP Inc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.jeansantos38.stf 8 | smart-test-framework 9 | pom 10 | 1.3-SNAPSHOT 11 | 12 | Smart-Test-Framework 13 | https://github.com/HPInc/smart-test-framework 14 | 15 | 16 | UTF-8 17 | 2.18.1 18 | 19 | 20 | 21 | jcenter 22 | bintray 23 | https://oss.sonatype.org/content/repositories/snapshots 24 | 25 | 26 | 27 | 28 | stf-misc-lib 29 | stf-http-client-lib 30 | stf-desktop-automation-lib 31 | stf-webdriver-lib 32 | 33 | 34 | 35 | 36 | 37 | org.testng 38 | testng 39 | 7.7.0-SNAPSHOT 40 | compile 41 | 42 | 43 | 44 | io.qameta.allure 45 | allure-testng 46 | 2.20.1 47 | 48 | 49 | com.google.guava 50 | guava 51 | [24.1.1,) 52 | compile 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-compiler-plugin 61 | 3.1 62 | 63 | 1.8 64 | 1.8 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-dependency-plugin 70 | 3.1.1 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /readme-img/installingLibsViaMvn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/readme-img/installingLibsViaMvn.png -------------------------------------------------------------------------------- /readme-img/stf_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/readme-img/stf_architecture.png -------------------------------------------------------------------------------- /readme-img/stf_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/readme-img/stf_logo.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | com.github.jeansantos38.stf 7 | smart-test-framework 8 | 1.3-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | stf-desktop-automation 13 | 1.3-SNAPSHOT 14 | jar 15 | STF-Desktop-Automation 16 | https://github.com/HPInc/smart-test-framework 17 | 18 | 19 | 20 | 21 | com.github.jeansantos38.stf 22 | stf-misc 23 | 1.3.1-SNAPSHOT 24 | 25 | 26 | 27 | 28 | com.sikulix 29 | sikulixapi 30 | 2.0.4 31 | 32 | 33 | 34 | 35 | 36 | org.apache.maven.plugins 37 | maven-surefire-plugin 38 | ${maven.surefire.plugin.version} 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/contants/ui/LogMessages.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.contants.ui; 2 | 3 | public class LogMessages { 4 | 5 | public static final String ERROR_PATTERN_NOT_FOUND_IN_REGION = "The expected pattern ***was not found*** inside the requested region\\area"; 6 | public static final String ERROR_PATTERN_FOUND_IN_REGION = "The expected pattern ***was found*** inside the requested region\\area."; 7 | public static final String ERROR_TEXT_NOT_FOUND_VIA_CLIPBOARD = "Text was not found when extracted via Clipboard!"; 8 | public static final String ERROR_TEXT_NOT_FOUND_VIA_OCR = "Text was not found when extracted via OCR!"; 9 | public static final String ERROR_SUFFIX_EXPECTED_ACTUAL = "\n[Expected:] %s\n[Actual:] %s"; 10 | public static final String NOT_VISIBLE_ASSERT_MSG = "The Ui element was not found! See logs for more details!"; 11 | public static final String STILL_VISIBLE_ASSERT_MSG = "The Ui element is still visible! See logs for more details!"; 12 | 13 | 14 | } 15 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/data/classes/ui/Details.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.data.classes.ui; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | /************************************************************ 6 | * © Copyright 2019 HP Development Company, L.P. 7 | * SPDX-License-Identifier: MIT 8 | * 9 | * Smart Test Framework 10 | ************************************************************/ 11 | 12 | @JsonIgnoreProperties(ignoreUnknown = true) 13 | public class Details { 14 | 15 | public String selector; 16 | public String imagePath; 17 | public String ctrlType; 18 | public String interactionType; 19 | public int xCoordinate; 20 | public int yCoordinate; 21 | public int regionTopLeftX; 22 | public int regionTopLeftY; 23 | public int regionBottomRightX; 24 | public int regionBottomRightY; 25 | public double similarity; 26 | 27 | public Details() { 28 | } 29 | 30 | public Details( String imagePath) { 31 | this.imagePath = imagePath; 32 | } 33 | 34 | public Details(String imagePath, int xCoordinate, int yCoordinate, double similarity) { 35 | this.imagePath = imagePath; 36 | this.xCoordinate = xCoordinate; 37 | this.yCoordinate = yCoordinate; 38 | this.similarity = similarity; 39 | } 40 | 41 | public Details(String imagePath, double similarity) { 42 | this.imagePath = imagePath; 43 | this.similarity = similarity; 44 | } 45 | 46 | public Details(String selector, String imagePath, String ctrlType, String interactionType, int xCoordinate, int yCoordinate, int regionTopLeftX, int regionTopLeftY, int regionBottomRightX, int regionBottomRightY, double similarity) { 47 | this.selector = selector; 48 | this.imagePath = imagePath; 49 | this.ctrlType = ctrlType; 50 | this.interactionType = interactionType; 51 | this.xCoordinate = xCoordinate; 52 | this.yCoordinate = yCoordinate; 53 | this.regionTopLeftX = regionTopLeftX; 54 | this.regionTopLeftY = regionTopLeftY; 55 | this.regionBottomRightX = regionBottomRightX; 56 | this.regionBottomRightY = regionBottomRightY; 57 | this.similarity = similarity; 58 | } 59 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/data/classes/ui/Element.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.data.classes.ui; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | 10 | public class Element { 11 | public Details details; 12 | public Element() { 13 | } 14 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/data/classes/ui/Navigator.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.data.classes.ui; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | 10 | public class Navigator { 11 | public NavigatorArea[] navigatorAreas; 12 | } 13 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/data/classes/ui/NavigatorArea.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.data.classes.ui; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | /************************************************************ 6 | * © Copyright 2019 HP Development Company, L.P. 7 | * SPDX-License-Identifier: MIT 8 | * 9 | * Smart Test Framework 10 | ************************************************************/ 11 | 12 | @JsonIgnoreProperties(ignoreUnknown = true) 13 | public class NavigatorArea { 14 | public String areaId; 15 | public Element[] elements; 16 | public NavigatorArea() { 17 | } 18 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/enums/UiAction.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum UiAction { 10 | CLICK, DOUBLE_CLICK, TRIPLE_CLICK, DRAG_AND_DROP, FIND, WAIT_FOR, EXISTS 11 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/enums/UiControls.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums; 2 | 3 | public enum UiControls { 4 | REGION, 5 | PICTURE, 6 | TEXT_BOX, 7 | CHECK_BOX, 8 | RADIO_BUTTON, 9 | BUTTON, 10 | TRACK_BAR, 11 | DEFAULT 12 | } 13 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/enums/UiMouseButton.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums; 2 | 3 | public enum UiMouseButton { 4 | RIGHT, LEFT, MIDDLE, WHEEL_UP,WHEEL_DOWN 5 | } 6 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/framework/ui/UiAutomationDriver.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.ui; 2 | 3 | import com.github.jeansantos38.stf.data.classes.ui.Details; 4 | import com.github.jeansantos38.stf.data.classes.ui.Element; 5 | import com.github.jeansantos38.stf.framework.logger.TestLog; 6 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 7 | import org.sikuli.script.FindFailed; 8 | 9 | import java.io.File; 10 | import java.io.IOException; 11 | 12 | /************************************************************ 13 | * © Copyright 2019 HP Development Company, L.P. 14 | * SPDX-License-Identifier: MIT 15 | * 16 | * Smart Test Framework 17 | ************************************************************/ 18 | public class UiAutomationDriver { 19 | 20 | private Object screen; 21 | private TestLog testLog; 22 | private final double SURE_MATCH_MIN_SCORE = 0.92; 23 | private final int MS_DELAY_BETWEEN_ACTIONS = 500; 24 | private final int MS_DELAY_BETWEEN_CLICKS = 200; 25 | private String folderPathToSaveScreenshots; 26 | private boolean takeScreenshotWhenFail; 27 | private WaitHelper waitHelper; 28 | private int msDelayBetweenClicks; 29 | private int msDelayBetweenActions; 30 | private UiVisualFeedback uiVisualFeedback; 31 | 32 | 33 | public UiAutomationDriver( 34 | Object screen, 35 | TestLog testLog, 36 | WaitHelper waitHelper, 37 | String folderPathToSaveScreenshots, 38 | boolean takeScreenshotWhenFail) throws Exception { 39 | this(screen, testLog, waitHelper, folderPathToSaveScreenshots, takeScreenshotWhenFail, 100, 100); 40 | } 41 | 42 | public UiAutomationDriver( 43 | Object screen, 44 | TestLog testLog, 45 | WaitHelper waitHelper, 46 | String folderPathToSaveScreenshots, 47 | boolean takeScreenshotWhenFail, 48 | UiVisualFeedback uiVisualFeedback) throws Exception { 49 | this(screen, testLog, waitHelper, folderPathToSaveScreenshots, takeScreenshotWhenFail, 100, 100, uiVisualFeedback); 50 | } 51 | 52 | public UiAutomationDriver( 53 | Object screen, 54 | TestLog testLog, 55 | WaitHelper waitHelper, 56 | String folderPathToSaveScreenshots, 57 | boolean takeScreenshotWhenFail, 58 | int msDelayBetweenClicks, 59 | int msDelayBetweenActions) throws Exception { 60 | this(screen, testLog, waitHelper, folderPathToSaveScreenshots, takeScreenshotWhenFail, msDelayBetweenClicks, msDelayBetweenActions, null); 61 | } 62 | 63 | public UiAutomationDriver( 64 | Object screen, 65 | TestLog testLog, 66 | WaitHelper waitHelper, 67 | String folderPathToSaveScreenshots, 68 | boolean takeScreenshotWhenFail, 69 | int msDelayBetweenClicks, 70 | int msDelayBetweenActions, 71 | UiVisualFeedback uiVisualFeedback) throws Exception { 72 | 73 | this.screen = screen; 74 | this.testLog = testLog; 75 | this.folderPathToSaveScreenshots = folderPathToSaveScreenshots; 76 | this.takeScreenshotWhenFail = takeScreenshotWhenFail; 77 | this.waitHelper = waitHelper; 78 | this.msDelayBetweenActions = msDelayBetweenActions == 0 ? MS_DELAY_BETWEEN_ACTIONS : msDelayBetweenActions; 79 | this.msDelayBetweenClicks = msDelayBetweenClicks == 0 ? MS_DELAY_BETWEEN_CLICKS : msDelayBetweenClicks; 80 | this.uiVisualFeedback = uiVisualFeedback; 81 | checkScreen(screen); 82 | } 83 | 84 | public UiElement buildPatternFromNavigator(String navFilePath, String areaId, String selector) throws Exception { 85 | return retrievePatternFromNavigatorString(navFilePath, areaId, selector); 86 | } 87 | 88 | public UiElement buildPattern(String imagePath) { 89 | return factory(this.screen, new Details(imagePath, 0, 0, SURE_MATCH_MIN_SCORE)); 90 | } 91 | 92 | public UiElement buildPattern(String imagePath, Double similarity) { 93 | return factory(this.screen, new Details(imagePath, 0, 0, similarity)); 94 | } 95 | 96 | public UiElement buildPattern(String imagePath, int xCoordinate, int yCoordinate) { 97 | return factory(this.screen, new Details(imagePath, xCoordinate, yCoordinate, SURE_MATCH_MIN_SCORE)); 98 | } 99 | 100 | public UiElement buildPattern(String imagePath, int xCoordinate, int yCoordinate, Double similarity) { 101 | return factory(this.screen, new Details(imagePath, xCoordinate, yCoordinate, similarity)); 102 | } 103 | 104 | public String takeScreenshot() throws IOException { 105 | return UiAutomationUtils.saveDesktopScreenshot(this.screen, this.folderPathToSaveScreenshots); 106 | } 107 | 108 | public String takeScreenshot(String filename) throws IOException { 109 | return UiAutomationUtils.saveDesktopScreenshot(this.screen, this.folderPathToSaveScreenshots, filename); 110 | } 111 | 112 | public void type(String... content) throws InterruptedException, FindFailed { 113 | StringBuilder finalContent = new StringBuilder(); 114 | for (String a : content) finalContent.append(a); 115 | UiAutomationUtils.type(this.screen, finalContent.toString()); 116 | } 117 | 118 | public void paste(String content) { 119 | UiAutomationUtils.paste(this.screen, content); 120 | } 121 | 122 | private UiElement retrievePatternFromNavigatorString(String navigatorFileFullPath, String areaId, String selector) throws Exception { 123 | Element element = UiAutomationUtils.retrievePatternFromNavigatorString(navigatorFileFullPath, areaId, selector); 124 | File navigator = new File(navigatorFileFullPath); 125 | element.details.imagePath = navigator.getAbsolutePath().replace(navigator.getName(), element.details.imagePath); 126 | return factory(this.screen, 127 | element.details); 128 | } 129 | 130 | private UiElement factory(Object screen, 131 | Details details) { 132 | return new UiElement(screen, 133 | details, 134 | this.msDelayBetweenClicks, 135 | this.msDelayBetweenActions, 136 | this.takeScreenshotWhenFail, 137 | this.folderPathToSaveScreenshots, 138 | this.uiVisualFeedback, 139 | this.waitHelper, 140 | this.testLog); 141 | } 142 | 143 | private void checkScreen(Object screen) throws Exception { 144 | if (screen == null) 145 | throw new Exception("Screen cannot be null!"); 146 | } 147 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/framework/ui/UiAutomationUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.ui; 2 | 3 | import com.github.jeansantos38.stf.data.classes.ui.Element; 4 | import com.github.jeansantos38.stf.data.classes.ui.Navigator; 5 | import com.github.jeansantos38.stf.data.classes.ui.NavigatorArea; 6 | import com.github.jeansantos38.stf.enums.serialization.SerializationType; 7 | import com.github.jeansantos38.stf.enums.wait.ThreadWait; 8 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 9 | import com.github.jeansantos38.stf.framework.logger.TestLog; 10 | import com.github.jeansantos38.stf.framework.misc.CalendarHelper; 11 | import com.github.jeansantos38.stf.framework.misc.RandomValuesHelper; 12 | import com.github.jeansantos38.stf.framework.serialization.DeserializeHelper; 13 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 14 | import org.sikuli.script.Screen; 15 | import org.sikuli.vnc.VNCScreen; 16 | 17 | import java.awt.*; 18 | import java.awt.datatransfer.Clipboard; 19 | import java.awt.datatransfer.DataFlavor; 20 | import java.awt.datatransfer.Transferable; 21 | import java.awt.datatransfer.UnsupportedFlavorException; 22 | import java.io.IOException; 23 | import java.util.Arrays; 24 | 25 | public class UiAutomationUtils { 26 | 27 | public static boolean isVncScreen(Object screen) { 28 | return !screen.getClass().equals(Screen.class); 29 | } 30 | 31 | public static void type(Object screen, String content) { 32 | if (isVncScreen(screen)) { 33 | ((VNCScreen) screen).type(content); 34 | } else { 35 | ((Screen) screen).type(content); 36 | } 37 | } 38 | 39 | public static void performKeyCombination(Object screen, String key, int... modifiers) throws InterruptedException { 40 | int finalModifiers = 0; 41 | for (int modifier : modifiers) { 42 | finalModifiers += modifier; 43 | } 44 | if (UiAutomationUtils.isVncScreen(screen)) { 45 | ((VNCScreen) screen).type(key, finalModifiers); 46 | } else { 47 | new WaitHelper().waitMilliseconds(5000); 48 | ((Screen) screen).type(key, finalModifiers); 49 | } 50 | } 51 | 52 | public static String getContentFromClipboard() { 53 | Clipboard cb = Toolkit.getDefaultToolkit() 54 | .getSystemClipboard(); 55 | try { 56 | Transferable t = cb.getContents(null); 57 | if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) 58 | return (String) t.getTransferData(DataFlavor 59 | .stringFlavor); 60 | } catch (IOException | UnsupportedFlavorException ex) { 61 | System.out.println("ZICOU"); 62 | } 63 | return null; 64 | } 65 | 66 | public static void paste(Object screen, String content) { 67 | if (UiAutomationUtils.isVncScreen(screen)) { 68 | ((VNCScreen) screen).paste(content); 69 | } else { 70 | ((Screen) screen).paste(content); 71 | } 72 | } 73 | 74 | public static String saveDesktopScreenshot(Object screen, String folderPath) throws IOException { 75 | String filename_prefix = RandomValuesHelper.generateAlphabetic(10); 76 | String filename_suffix = CalendarHelper.getCurrentTimeAndDate(); 77 | return saveDesktopScreenshot(screen, folderPath, filename_prefix + filename_suffix); 78 | } 79 | 80 | static String saveDesktopScreenshot(Object screen, String folderPath, String filename) throws IOException { 81 | String path = InputOutputHelper.createDirectory(folderPath); 82 | if (UiAutomationUtils.isVncScreen(screen)) { 83 | return ((VNCScreen) screen).capture().save(path, filename); 84 | } else { 85 | return ((Screen) screen).capture().save(path, filename); 86 | } 87 | } 88 | 89 | public static VNCScreen connectToVncScreen(String vncServerIpAddress, int vncServerPort, String vncServerPassword, int connectionTimeoutSec, int operationTimeoutMs, int retryAttempts) throws Exception { 90 | int counter = 0; 91 | VNCScreen vncScreen; 92 | while (counter < retryAttempts) { 93 | vncScreen = VNCScreen.start(vncServerIpAddress, vncServerPort, vncServerPassword, connectionTimeoutSec, operationTimeoutMs); 94 | if (vncScreen.getClient() == null) { 95 | counter++; 96 | new WaitHelper().wait(ThreadWait.WAIT_3_SEC); 97 | } else { 98 | return vncScreen; 99 | } 100 | } 101 | throw new Exception(String.format("It was not possible to establish a connection to VNC server %s:%s in %s attempts!", vncServerIpAddress, vncServerPort, retryAttempts)); 102 | } 103 | 104 | public static Element retrievePatternFromNavigatorString(String navigatorFileFullPath, String areaId, String selector) throws Exception { 105 | String navigatorContent = InputOutputHelper.readContentFromFile(navigatorFileFullPath); 106 | Navigator navigator = DeserializeHelper.deserializeStringToObject(Navigator.class, SerializationType.YAML, navigatorContent); 107 | NavigatorArea masterImageDetails = Arrays.stream(navigator.navigatorAreas).filter(x -> x.areaId.equals(areaId)).findAny().orElse(null); 108 | if (masterImageDetails == null) 109 | throw new Exception(String.format("The master image details for area '%1$s' was not retrieved from navigator, pls review the given parameters.", areaId)); 110 | Element element = Arrays.stream(masterImageDetails.elements).filter(x -> x.details.selector.equals(selector)).findFirst().orElse(null); 111 | if (element == null || element.details == null) 112 | throw new Exception(String.format("The element for selector '%1$s' was not retrieved from navigator, pls review the given parameters.", selector)); 113 | new TestLog().logIt(String.format("Searching for the image '%1$s' related to the selector '%2$s'.", element.details.imagePath, selector)); 114 | return element; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/framework/ui/UiVisualFeedback.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.ui; 2 | 3 | 4 | public class UiVisualFeedback { 5 | 6 | boolean enableHighlight; 7 | 8 | public boolean highlightEnabled() { 9 | return enableHighlight; 10 | } 11 | 12 | public void setEnableHighlight(boolean enableHighlight) { 13 | this.enableHighlight = enableHighlight; 14 | } 15 | 16 | String masterHighlightColor; 17 | String coordinateHighlightColor; 18 | String areaHighlightColor; 19 | double highlightTimeSec; 20 | int relHighlightH; 21 | int relHighlightW; 22 | 23 | public UiVisualFeedback() { 24 | this(true, "green", "red", "orange", 0.2, 0, 0); 25 | } 26 | 27 | public UiVisualFeedback( 28 | String masterHighlightColor, 29 | String coordinateHighlightColor, 30 | String areaHighlightColor) { 31 | this(true, masterHighlightColor, coordinateHighlightColor, areaHighlightColor, 0.2, 0, 0); 32 | 33 | } 34 | 35 | public UiVisualFeedback( 36 | String masterHighlightColor, 37 | String coordinateHighlightColor, 38 | String areaHighlightColor, 39 | double highlightTimeSec) { 40 | this(true, masterHighlightColor, coordinateHighlightColor, areaHighlightColor, highlightTimeSec, 0, 0); 41 | 42 | } 43 | 44 | public UiVisualFeedback( 45 | boolean enableHighlight, 46 | String masterHighlightColor, 47 | String coordinateHighlightColor, 48 | String areaHighlightColor, 49 | double highlightTimeSec, 50 | int relHighlightH, 51 | int relHighlightW) { 52 | this.enableHighlight = enableHighlight; 53 | this.masterHighlightColor = masterHighlightColor; 54 | this.coordinateHighlightColor = coordinateHighlightColor; 55 | this.areaHighlightColor = areaHighlightColor; 56 | this.highlightTimeSec = highlightTimeSec; 57 | int HIGHLIGHT_DEFAULT_SIZE = 1; 58 | this.relHighlightH = relHighlightH == 0 ? HIGHLIGHT_DEFAULT_SIZE : relHighlightH; 59 | this.relHighlightW = relHighlightW == 0 ? HIGHLIGHT_DEFAULT_SIZE : relHighlightW; 60 | } 61 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/java/system/base/MainTestBase.java: -------------------------------------------------------------------------------- 1 | package system.base; 2 | 3 | 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 6 | import org.testng.annotations.BeforeClass; 7 | import org.testng.annotations.Optional; 8 | import org.testng.annotations.Parameters; 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class MainTestBase { 17 | 18 | protected static TestLog testLog; 19 | protected WaitHelper waitHelper; 20 | 21 | @BeforeClass 22 | @Parameters({"optionalGlobalParameterExample"}) 23 | public void mainTestBaseInitialize(@Optional("") String param1) throws Exception { 24 | testLog = new TestLog(true); 25 | testLog.logIt("Parameter value provided from testRunConfig:" + param1); 26 | waitHelper = new WaitHelper(); 27 | } 28 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/java/system/base/UiAutomationTestBase.java: -------------------------------------------------------------------------------- 1 | package system.base; 2 | 3 | import com.github.jeansantos38.stf.enums.wait.ThreadWait; 4 | 5 | import java.io.File; 6 | import java.io.IOException; 7 | 8 | public class UiAutomationTestBase extends MainTestBase { 9 | 10 | protected String discoverAbsoluteFilePath(String filename) { 11 | return new File(String.format("src/test/resources/%s", filename)).getAbsolutePath(); 12 | } 13 | 14 | protected void startWinDemoApp() throws Exception { 15 | String stf_win_app_demo = discoverAbsoluteFilePath("bin/SmartTestFrameworkDemo.exe"); 16 | Runtime.getRuntime().exec(String.format("cmd /c %s", stf_win_app_demo)); 17 | waitHelper.wait(ThreadWait.WAIT_3_SEC); 18 | } 19 | 20 | protected void endWinDemoApp() throws Exception { 21 | Runtime.getRuntime().exec("taskkill /F /IM \"SmartTestFrameworkDemo.exe\" /T"); 22 | waitHelper.wait(ThreadWait.WAIT_5_SEC); 23 | } 24 | 25 | protected void manageVm(String msg, String script, String vmManagerBinPath, String vmName, String vmSnapshotName) throws IOException { 26 | String fullCommand = String.format("cmd /c %s \"%s\" \"%s\" \"%s\"", script, vmManagerBinPath, vmName, vmSnapshotName); 27 | testLog.logIt(msg + "\n" + fullCommand); 28 | Runtime.getRuntime().exec(fullCommand); 29 | } 30 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/java/system/test/UiAutomationBasic.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.ui.UiAutomationDriver; 4 | import com.github.jeansantos38.stf.framework.ui.UiElement; 5 | import org.sikuli.hotkey.Keys; 6 | import org.sikuli.script.FindFailed; 7 | import org.sikuli.script.Screen; 8 | import org.testng.Assert; 9 | import org.testng.annotations.AfterMethod; 10 | import org.testng.annotations.BeforeClass; 11 | import org.testng.annotations.BeforeMethod; 12 | import org.testng.annotations.Test; 13 | import system.base.UiAutomationTestBase; 14 | 15 | import java.io.IOException; 16 | 17 | public class UiAutomationBasic extends UiAutomationTestBase { 18 | 19 | UiAutomationDriver uiAutomationDriver; 20 | String radioBtn2ImgUnchecked; 21 | String textBoxFilledImg; 22 | String radioBtn2ImgChecked; 23 | String textBoxDefaultImg; 24 | String stfIcoImg; 25 | 26 | @BeforeClass 27 | public void beforeClass() throws Exception { 28 | Screen screen = new Screen(); 29 | uiAutomationDriver = new UiAutomationDriver(screen, testLog, waitHelper, System.getProperty("user.home") + "/STF_Screenshots", true); 30 | radioBtn2ImgUnchecked = discoverAbsoluteFilePath("masters/winApp/radioButton2_unchecked.png"); 31 | radioBtn2ImgChecked = discoverAbsoluteFilePath("masters/winApp/radioButton2_checked.png"); 32 | textBoxFilledImg = discoverAbsoluteFilePath("masters/winApp/textBox2_filled.png"); 33 | textBoxDefaultImg = discoverAbsoluteFilePath("masters/winApp/textBox2_default.png"); 34 | stfIcoImg = discoverAbsoluteFilePath("masters/winApp/stf_ico.png"); 35 | } 36 | 37 | @AfterMethod 38 | public void runAfterEachTest() throws Exception { 39 | testLog.logIt("Closing the app"); 40 | endWinDemoApp(); 41 | } 42 | 43 | @BeforeMethod 44 | public void runBeforeEachTest() throws Exception { 45 | testLog.logIt("Open the app"); 46 | startWinDemoApp(); 47 | } 48 | 49 | @Test 50 | public void radioButtonTest() throws Exception { 51 | UiElement radioBtn2Unchecked = uiAutomationDriver.buildPattern(radioBtn2ImgUnchecked, 0.99); 52 | radioBtn2Unchecked.assertVisible(); 53 | radioBtn2Unchecked.assertVisible(2000); 54 | radioBtn2Unchecked.click(); 55 | uiAutomationDriver.buildPattern(stfIcoImg).moveCursorOver(); 56 | /* 57 | Once clicked the original pattern won't exist anymore, since the original img is not selected. 58 | */ 59 | radioBtn2Unchecked.assertNotVisible(2000); 60 | radioBtn2Unchecked.assertNotVisible(); 61 | uiAutomationDriver.buildPattern(radioBtn2ImgChecked, 0.99).assertVisible(); 62 | } 63 | 64 | @Test 65 | public void textBoxTest1() throws Exception { 66 | UiElement textBox2 = uiAutomationDriver.buildPattern(textBoxDefaultImg, 0.95); 67 | textBox2.assertVisible(2000); 68 | textBox2.doubleClick(); 69 | textBox2.paste("this is a test"); 70 | uiAutomationDriver.type(Keys.TAB); 71 | uiAutomationDriver.buildPattern(textBoxFilledImg, 0.92).assertVisible(2000); 72 | textBox2.assertNotVisible(); 73 | } 74 | 75 | @Test 76 | public void checkNonExistentPattern() throws IOException, FindFailed { 77 | UiElement uiElement = uiAutomationDriver.buildPattern(textBoxFilledImg); 78 | try { 79 | uiElement.assertVisible(1000); 80 | } catch (AssertionError a) { 81 | Assert.assertTrue(a.getMessage().contains(uiElement.get_NOT_VISIBLE_ASSERT_MSG())); 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/java/system/test/UiAutomationGeneric.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.misc.VisualWarningsHelper; 4 | import com.github.jeansantos38.stf.framework.ui.UiAutomationDriver; 5 | import com.github.jeansantos38.stf.framework.ui.UiAutomationUtils; 6 | import com.github.jeansantos38.stf.framework.ui.UiElement; 7 | import com.github.jeansantos38.stf.framework.ui.UiVisualFeedback; 8 | import com.github.jeansantos38.stf.framework.misc.RandomValuesHelper; 9 | import org.sikuli.script.Screen; 10 | import org.sikuli.vnc.VNCScreen; 11 | import org.testng.annotations.*; 12 | import system.base.UiAutomationTestBase; 13 | 14 | public class UiAutomationGeneric extends UiAutomationTestBase { 15 | 16 | UiAutomationDriver uiAutomationDriver; 17 | String navigator; 18 | String startVmScript; 19 | String endVmScript; 20 | String vmManagerBinPath; 21 | String vmName; 22 | String vmSnapshotName; 23 | boolean isVncScreen; 24 | boolean popUpDuringTest; 25 | 26 | 27 | @Parameters({"_isVncScreen", 28 | "_vmManagerBinPath", 29 | "_vmName", 30 | "_vmSnapshotName", 31 | "_vncServerIpAddress", 32 | "_vncServerPort", 33 | "_vncServerPassword", 34 | "_connectionTimeoutSec", 35 | "_operationTimeoutMs", 36 | "_popUpDuringTest"}) 37 | @BeforeClass 38 | public void beforeClass(@Optional("false") Boolean _isVncScreen, 39 | @Optional("") String _vmManagerBinPath, 40 | @Optional("") String _vmName, 41 | @Optional("") String _vmSnapshotName, 42 | @Optional("") String _vncServerIpAddress, 43 | @Optional("5900") Integer _vncServerPort, 44 | @Optional("") String _vncServerPassword, 45 | @Optional("15") Integer _connectionTimeoutSec, 46 | @Optional("3000") Integer _operationTimeoutMs, 47 | @Optional("false") Boolean _popUpDuringTest) throws Exception { 48 | navigator = discoverAbsoluteFilePath("masters/winApp/_navigator_STF_Win_Demo-App.yml"); 49 | startVmScript = discoverAbsoluteFilePath("scripts/vBoxStartVmSnapshot.bat"); 50 | endVmScript = discoverAbsoluteFilePath("scripts/vBoxShutdownVmRestoreSnapshot.bat"); 51 | isVncScreen = _isVncScreen; 52 | vmManagerBinPath = _vmManagerBinPath; 53 | vmName = _vmName; 54 | vmSnapshotName = _vmSnapshotName; 55 | popUpDuringTest = _popUpDuringTest; 56 | 57 | UiVisualFeedback uiVisualFeedback = new UiVisualFeedback("green", "red", "blue", 0.2); 58 | uiVisualFeedback.setEnableHighlight(true); 59 | 60 | if (!_isVncScreen) { 61 | uiAutomationDriver = new UiAutomationDriver(new Screen(), testLog, waitHelper, System.getProperty("user.home") + "/STF_Screenshots", true, 500, 500, uiVisualFeedback); 62 | startWinDemoApp(); 63 | } else { 64 | manageVm("Starting test VM!", startVmScript, _vmManagerBinPath, _vmName, _vmSnapshotName); 65 | VNCScreen screen = UiAutomationUtils.connectToVncScreen(_vncServerIpAddress, _vncServerPort, _vncServerPassword, _connectionTimeoutSec, _operationTimeoutMs, 3); 66 | uiAutomationDriver = new UiAutomationDriver(screen, testLog, waitHelper, System.getProperty("user.home") + "/STF_Screenshots", true, uiVisualFeedback); 67 | uiAutomationDriver.buildPatternFromNavigator(navigator, "desktop", "stfIcon").doubleClick(); 68 | } 69 | } 70 | 71 | @AfterClass 72 | public void cleanup() throws Exception { 73 | if (!isVncScreen) { 74 | endWinDemoApp(); 75 | } else { 76 | manageVm("Ending test VM!", endVmScript, vmManagerBinPath, vmName, vmSnapshotName); 77 | } 78 | } 79 | 80 | @Test 81 | public void demoTest() throws Exception { 82 | String testMsg = "This is a super demo test!"; 83 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "innerIco").assertVisible(3000); 84 | 85 | UiElement textBox1 = uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "textBox1Region"); 86 | textBox1.clearText(); 87 | textBox1.type(testMsg); 88 | 89 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "cbx_1").click(); 90 | 91 | if (popUpDuringTest) 92 | VisualWarningsHelper.showDialogInfo("Pause!", "Move the form around!", 1); 93 | 94 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "cbx_2").click(); 95 | 96 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "dropdownLst").click(); 97 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "dropdownLst_item5").click(); 98 | 99 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "rbt_2").click(); 100 | if (popUpDuringTest) 101 | VisualWarningsHelper.showDialogInfo("Pause!", "Move the form around!", 1); 102 | 103 | UiElement textBox2 = uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "textBox2Region"); 104 | textBox2.clearText(); 105 | String randomMsg = "wow a random value -> " + RandomValuesHelper.generateRandomAlphanumeric(20); 106 | textBox2.type(randomMsg); 107 | 108 | 109 | UiElement trackbarOpt1 = uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "tbr_value1"); 110 | UiElement trackbarOpt2 = uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "tbr_value3"); 111 | 112 | trackbarOpt1.dragAndDrop(trackbarOpt2); 113 | 114 | uiAutomationDriver.buildPatternFromNavigator(navigator, "mainScreen", "x_close_btn").click(); 115 | 116 | } 117 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/java/system/test/UiAutomationVisibility.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.ui.UiAutomationDriver; 4 | import com.github.jeansantos38.stf.framework.ui.UiElement; 5 | import com.github.jeansantos38.stf.framework.ui.UiVisualFeedback; 6 | import org.sikuli.script.Screen; 7 | import org.testng.Assert; 8 | import org.testng.annotations.BeforeClass; 9 | import org.testng.annotations.Test; 10 | import system.base.UiAutomationTestBase; 11 | 12 | public class UiAutomationVisibility extends UiAutomationTestBase { 13 | 14 | UiAutomationDriver uiAutomationDriver; 15 | String navigator; 16 | UiElement stfIcon; 17 | 18 | @BeforeClass 19 | public void beforeClass() throws Exception { 20 | navigator = discoverAbsoluteFilePath("masters/winApp/_navigator_STF_Win_Demo-App.yml"); 21 | UiVisualFeedback uiVisualFeedback = new UiVisualFeedback(); 22 | uiVisualFeedback.setEnableHighlight(true); 23 | uiAutomationDriver = new UiAutomationDriver(new Screen(), testLog, waitHelper, System.getProperty("user.home") + "/STF_Screenshots", true, 500, 500, uiVisualFeedback); 24 | stfIcon = uiAutomationDriver.buildPatternFromNavigator(navigator, "desktop", "innerIco"); 25 | } 26 | 27 | @BeforeClass 28 | public void initializeApp() throws Exception { 29 | endWinDemoApp(); 30 | } 31 | 32 | @Test 33 | public void waitExistsTest() throws Exception { 34 | try { 35 | stfIcon.waitExists(1, true); 36 | } catch (Exception e) { 37 | Assert.assertTrue(e.getMessage().contains("stf_ico.png")); 38 | } 39 | startWinDemoApp(); 40 | stfIcon.waitExists(5, true); 41 | } 42 | 43 | 44 | @Test(dependsOnMethods = {"waitExistsTest"}) 45 | public void waitVanishesTest() throws Exception { 46 | try { 47 | stfIcon.waitVanishes(5, true); 48 | } catch (Exception e) { 49 | testLog.logIt(e.getMessage()); 50 | } 51 | endWinDemoApp(); 52 | stfIcon.waitVanishes(5, true); 53 | } 54 | } -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/bin/SmartTestFrameworkDemo.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/bin/SmartTestFrameworkDemo.exe -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_false.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_cbx_true.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx1.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_cbx2.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_ddl_item2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_ddl_item2.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_rbt2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_rbt2.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_tbr_value2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_tbr_value2.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb1.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_assert_txb2.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_item3_inList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_dd_item3_inList.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_false.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/mst_winformSTFdemo_v1-0_1920x1080_Win-10_rbt_true.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/reg_checkBox1_default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/reg_checkBox1_default.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/topBar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/imgrDatadriven/desktop-apps/winformSTFdemo/1.0/topBar.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/checkbox_false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/checkbox_false.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/checkbox_true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/checkbox_true.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/notExistentPattern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/notExistentPattern.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/radiobutton_false.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/radiobutton_false.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/radiobutton_true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/radiobutton_true.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/stf_ico.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/stf_ico.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/masters/winApp/trackbarPointer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HPInc/smart-test-framework/aa582ad018250452ab35e92b56e8e397097c17ff/stf-desktop-automation-lib/src/test/resources/masters/winApp/trackbarPointer.png -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/scripts/vBoxShutdownVmRestoreSnapshot.bat: -------------------------------------------------------------------------------- 1 | @ECHO ON 2 | %1 controlvm %2 poweroff 3 | %1 snapshot %2 restore %3 -------------------------------------------------------------------------------- /stf-desktop-automation-lib/src/test/resources/scripts/vBoxStartVmSnapshot.bat: -------------------------------------------------------------------------------- 1 | @ECHO ON 2 | %1 snapshot %2 restore %3 3 | %1 startvm %2 restore %3 -------------------------------------------------------------------------------- /stf-desktop-automation-lib/testRunConfig/testRunConfig_ui-auto-local.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /stf-desktop-automation-lib/testRunConfig/testRunConfig_ui-auto-remote.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /stf-http-client-lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | com.github.jeansantos38.stf 8 | smart-test-framework 9 | 1.3-SNAPSHOT 10 | 11 | 4.0.0 12 | 13 | stf-http-client 14 | 1.3-SNAPSHOT 15 | jar 16 | 17 | STF-Http-Client 18 | https://github.com/HPInc/smart-test-framework 19 | 20 | 21 | 22 | 23 | com.github.jeansantos38.stf 24 | stf-misc 25 | 1.3.1-SNAPSHOT 26 | 27 | 28 | org.apache.httpcomponents 29 | httpcore 30 | 4.4.3 31 | 32 | 33 | org.apache.httpcomponents 34 | httpclient 35 | 4.5.13 36 | 37 | 38 | org.apache.httpcomponents 39 | httpasyncclient 40 | 4.0.2 41 | 42 | 43 | org.apache.httpcomponents 44 | httpmime 45 | 4.3.6 46 | 47 | 48 | 49 | 50 | com.github.tomakehurst 51 | wiremock-standalone 52 | 2.23.2 53 | test 54 | 55 | 56 | 57 | 58 | com.jayway.jsonpath 59 | json-path 60 | 2.4.0 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-surefire-plugin 69 | ${maven.surefire.plugin.version} 70 | 71 | 72 | testRunConfig/testRunConfig_http-client_rest_demo-tests.xml 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/web/http/HttpDetailedHeader.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.web.http; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | 10 | public class HttpDetailedHeader { 11 | public String headerKey; 12 | public String headerValue; 13 | 14 | public HttpDetailedHeader() { 15 | } 16 | 17 | public HttpDetailedHeader(String headerKey, String headerValue) { 18 | this.headerKey = headerKey; 19 | this.headerValue = headerValue; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/web/http/HttpDetailedHeaders.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.web.http; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /************************************************************ 8 | * © Copyright 2019 HP Development Company, L.P. 9 | * SPDX-License-Identifier: MIT 10 | * 11 | * Smart Test Framework 12 | ************************************************************/ 13 | 14 | public class HttpDetailedHeaders { 15 | 16 | public List headerList; 17 | 18 | public HttpDetailedHeaders() { 19 | this.headerList = new ArrayList<>(); 20 | } 21 | 22 | public HttpDetailedHeaders(List headerList) { 23 | this.headerList = headerList; 24 | } 25 | 26 | /** 27 | * Convert old STF headers into new Version 28 | * 29 | * @param headers 30 | * @return 31 | */ 32 | public static HttpDetailedHeaders convertLegacyHeaders(Map headers) { 33 | HttpDetailedHeaders httpDetailedHeaders = new HttpDetailedHeaders(); 34 | for (Map.Entry entry : headers.entrySet()) { 35 | httpDetailedHeaders.headerList.add(new HttpDetailedHeader(entry.getKey(), entry.getValue())); 36 | } 37 | return httpDetailedHeaders; 38 | } 39 | 40 | /** 41 | * Helper to check if a detailed header does exist in a list of headers. 42 | * 43 | * @param httpDetailedHeaders The headers from Http response 44 | * @param httpDetailedHeader The header you're looking for. If you don't provide an expected header value, it will check only if the header key exists. 45 | * @return 46 | */ 47 | public static boolean containsHeader(HttpDetailedHeaders httpDetailedHeaders, HttpDetailedHeader httpDetailedHeader) { 48 | if (httpDetailedHeader.headerValue != null && !httpDetailedHeader.headerValue.isEmpty()) { 49 | return httpDetailedHeaders.headerList.stream().filter(x -> x.headerKey.equals(httpDetailedHeader.headerKey) && x.headerValue.equals(httpDetailedHeader.headerValue)).findAny().orElse(null) != null; 50 | } else { 51 | return httpDetailedHeaders.headerList.stream().filter(x -> x.headerKey.equals(httpDetailedHeader.headerKey)).findAny().orElse(null) != null; 52 | } 53 | } 54 | 55 | /** 56 | * Helper to check if a given header key and value does exist in a list of headers. 57 | * 58 | * @param httpDetailedHeaders 59 | * @param headerKey 60 | * @param headerValue 61 | * @return 62 | */ 63 | public static boolean containsHeader(HttpDetailedHeaders httpDetailedHeaders, String headerKey, String headerValue) { 64 | HttpDetailedHeader httpDetailedHeader = new HttpDetailedHeader(headerKey, headerValue); 65 | return containsHeader(httpDetailedHeaders, httpDetailedHeader); 66 | } 67 | 68 | /** 69 | * It returns the token value for the first matching header key. 70 | * 71 | * @param httpDetailedHeaders 72 | * @param headerKey 73 | * @return 74 | * @throws Exception 75 | */ 76 | public static String getFirstMatchingHeader(HttpDetailedHeaders httpDetailedHeaders, String headerKey) throws Exception { 77 | return getFirstMatchingHeader(httpDetailedHeaders, true, headerKey); 78 | } 79 | 80 | /** 81 | * It returns the header key (name) for the first matching entry with the same provided header value. 82 | * 83 | * @param httpDetailedHeaders 84 | * @param headerValue 85 | * @return 86 | * @throws Exception 87 | */ 88 | public static String discoverHeaderKeyByValue(HttpDetailedHeaders httpDetailedHeaders, String headerValue) throws Exception { 89 | return getFirstMatchingHeader(httpDetailedHeaders, false, headerValue); 90 | } 91 | 92 | private static String getFirstMatchingHeader(HttpDetailedHeaders httpDetailedHeaders, boolean isKey, String value) throws Exception { 93 | HttpDetailedHeader httpDetailedHeader; 94 | 95 | if (isKey) { 96 | httpDetailedHeader = httpDetailedHeaders.headerList.stream().filter(x -> x.headerKey.equals(value)).findAny().orElse(null); 97 | return httpDetailedHeader == null ? null : httpDetailedHeader.headerValue; 98 | } else { 99 | httpDetailedHeader = httpDetailedHeaders.headerList.stream().filter(x -> x.headerValue.equals(value)).findAny().orElse(null); 100 | return httpDetailedHeader == null ? null : httpDetailedHeader.headerKey; 101 | } 102 | } 103 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/web/http/HttpDetailedRequest.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.web.http; 2 | 3 | import com.github.jeansantos38.stf.enums.http.HttpRequestLogLevel; 4 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 5 | import com.github.jeansantos38.stf.framework.httpclient.StatusCodeVerifier; 6 | 7 | /************************************************************ 8 | * © Copyright 2019 HP Development Company, L.P. 9 | * SPDX-License-Identifier: MIT 10 | * 11 | * Smart Test Framework 12 | ************************************************************/ 13 | 14 | public class HttpDetailedRequest { 15 | 16 | public HttpRequestMethod method; 17 | public String url; 18 | public Object headers; 19 | public byte[] payloadToBeSent; 20 | public StatusCodeVerifier statusCodeVerifier; 21 | public HttpRequestLogLevel logLevel; 22 | 23 | public HttpDetailedRequest() { 24 | this(null, null, null, null, null, HttpRequestLogLevel.LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE); 25 | } 26 | 27 | public HttpDetailedRequest(HttpRequestMethod method, String url, Object headers, byte[] payloadToBeSent, StatusCodeVerifier statusVerifier) { 28 | this(method, url, headers, payloadToBeSent, statusVerifier, HttpRequestLogLevel.LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE); 29 | } 30 | 31 | public HttpDetailedRequest(HttpRequestMethod method, String url, Object headers, byte[] payloadToBeSent, StatusCodeVerifier statusVerifier, HttpRequestLogLevel logLevel) { 32 | this.method = method; 33 | this.url = url; 34 | this.headers = headers; 35 | this.payloadToBeSent = payloadToBeSent; 36 | this.statusCodeVerifier = statusVerifier; 37 | this.logLevel = logLevel; 38 | } 39 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/web/http/HttpInternalResponse.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.web.http; 2 | 3 | import com.google.common.base.Stopwatch; 4 | import org.apache.http.HttpResponse; 5 | 6 | /************************************************************ 7 | * © Copyright 2019 HP Development Company, L.P. 8 | * SPDX-License-Identifier: MIT 9 | * 10 | * Smart Test Framework 11 | ************************************************************/ 12 | public class HttpInternalResponse { 13 | 14 | public Stopwatch stopwatch; 15 | public HttpResponse httpResponse; 16 | 17 | public HttpInternalResponse(Stopwatch stopwatch, HttpResponse httpResponse) { 18 | this.stopwatch = stopwatch; 19 | this.httpResponse = httpResponse; 20 | } 21 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/web/proxy/ProxySettings.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.web.proxy; 2 | 3 | 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | 6 | /************************************************************ 7 | * © Copyright 2019 HP Development Company, L.P. 8 | * SPDX-License-Identifier: MIT 9 | * 10 | * Smart Test Framework 11 | ************************************************************/ 12 | 13 | public class ProxySettings { 14 | 15 | public String proxyAddress; 16 | public int proxyPort; 17 | public String proxyUsername; 18 | public String proxyUserPassword; 19 | public boolean directInternetConnection; 20 | public boolean requireProxyAuthentication; 21 | private TestLog testLog; 22 | 23 | /*** 24 | * Class constructor. 25 | */ 26 | public ProxySettings() { 27 | this.testLog = new TestLog(); 28 | } 29 | 30 | /*** 31 | * Class constructor. 32 | */ 33 | public ProxySettings(boolean enableLogs) { 34 | this.testLog = new TestLog(enableLogs); 35 | this.directInternetConnection = true; 36 | } 37 | 38 | /*** 39 | * Helper to configure the ProxySettings. 40 | * @param proxyAddress: The proxy address. 41 | * @param proxyPort: Proxy port. 42 | * @param proxyUsername: Username for proxy authentication. 43 | * @param proxyUserPassword :Password for proxy authentication. 44 | */ 45 | public void configureProxySettings(String proxyAddress, String proxyPort, String proxyUsername, String proxyUserPassword) { 46 | if (proxyAddress != null && !proxyAddress.isEmpty()) { 47 | this.proxyAddress = proxyAddress; 48 | this.proxyPort = Integer.parseInt(proxyPort); 49 | } 50 | this.proxyUsername = proxyUsername.isEmpty() ? "" : proxyUsername; 51 | this.proxyUserPassword = proxyUserPassword.isEmpty() ? "" : proxyUserPassword; 52 | this.requireProxyAuthentication = !this.proxyUsername.isEmpty() || !proxyUserPassword.isEmpty() ? true : false; 53 | this.directInternetConnection = proxyAddress == null || proxyAddress.isEmpty() ? true : false; 54 | 55 | this.testLog.logIt(this.directInternetConnection ? "No proxy selected - direct internet connection" : String.format("The selected proxy was %1$s:%2$s", this.proxyAddress, Integer.toString(this.proxyPort))); 56 | if (this.requireProxyAuthentication) { 57 | this.testLog.logIt(String.format("Proxy user and password are respectively: [%1$s:%2$s]", proxyUsername, proxyUserPassword)); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/enums/http/HttpRequestLogLevel.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.http; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | 10 | public enum HttpRequestLogLevel { 11 | LOG_NOTHING, 12 | LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE, 13 | LOG_BASIC_INFO_ONLY_FROM_REQUEST_AND_RESPONSE, 14 | LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE_BUT_HEADERS, 15 | LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE_BUT_PAYLOAD 16 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/enums/http/HttpRequestMethod.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.http; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum HttpRequestMethod { 10 | GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD, TRACE 11 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/enums/http/StatusCodeVerifierStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.http; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | 10 | public enum StatusCodeVerifierStrategy { 11 | EXPECTED_STATUS_CODE, LIST_OF_POSSIBLE_STATUS_CODES, REGEX_FOR_POSSIBLE_STATUS_CODES 12 | } 13 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/framework/httpclient/HttpDeleteWithBody.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.httpclient; 2 | 3 | import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 4 | 5 | import java.net.URI; 6 | 7 | /************************************************************ 8 | * © Copyright 2019 HP Development Company, L.P. 9 | * SPDX-License-Identifier: MIT 10 | * 11 | * Smart Test Framework 12 | ************************************************************/ 13 | 14 | class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { 15 | 16 | public static final String METHOD_NAME = "DELETE"; 17 | 18 | /*** 19 | * Return the method name. 20 | * @return 21 | */ 22 | public String getMethod() { 23 | return METHOD_NAME; 24 | } 25 | 26 | /*** 27 | * Helper to perform a delete operation when the request does contain a payload. 28 | * @param uri: The uri to be accessed. 29 | */ 30 | public HttpDeleteWithBody(final String uri) { 31 | super(); 32 | setURI(URI.create(uri)); 33 | } 34 | 35 | /*** 36 | * Helper to perform a delete operation when the request does contain a payload. 37 | * @param uri: The uri to be accessed. 38 | */ 39 | public HttpDeleteWithBody(final URI uri) { 40 | super(); 41 | setURI(uri); 42 | } 43 | 44 | /*** 45 | * Helper to perform a delete operation when the request does contain a payload. 46 | */ 47 | public HttpDeleteWithBody() { 48 | super(); 49 | } 50 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/framework/httpclient/RequestsLogger.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.httpclient; 2 | 3 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedResponse; 4 | import com.github.jeansantos38.stf.enums.http.HttpRequestLogLevel; 5 | import com.github.jeansantos38.stf.framework.logger.TestLog; 6 | 7 | 8 | /************************************************************ 9 | * © Copyright 2019 HP Development Company, L.P. 10 | * SPDX-License-Identifier: MIT 11 | * 12 | * Smart Test Framework 13 | ************************************************************/ 14 | 15 | public class RequestsLogger { 16 | 17 | public static void LogHttpClientRequestInfo(TestLog testLog, HttpDetailedResponse httpDetailedResponse, HttpRequestLogLevel logLevel) throws Exception { 18 | 19 | switch (logLevel) { 20 | case LOG_NOTHING: 21 | break; 22 | case LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE: 23 | testLog.logIt(httpDetailedResponse.fullTransactionContentRaw); 24 | break; 25 | case LOG_BASIC_INFO_ONLY_FROM_REQUEST_AND_RESPONSE: 26 | testLog.logIt(httpDetailedResponse.getLogBasicInfoOnlyFromRequestAndResponse()); 27 | break; 28 | case LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE_BUT_HEADERS: 29 | testLog.logIt(httpDetailedResponse.getLogEverythingButHeaders()); 30 | break; 31 | case LOG_EVERYTHING_FROM_REQUEST_AND_RESPONSE_BUT_PAYLOAD: 32 | testLog.logIt(httpDetailedResponse.getLogEverythingButPayload()); 33 | break; 34 | default: 35 | throw new Exception(String.format("The log %s is not supported!", logLevel.toString())); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/main/java/com/github/jeansantos38/stf/framework/httpclient/StatusCodeVerifier.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.httpclient; 2 | 3 | import com.github.jeansantos38.stf.enums.http.StatusCodeVerifierStrategy; 4 | import com.github.jeansantos38.stf.framework.regex.RegexHelper; 5 | import org.testng.Assert; 6 | 7 | import java.util.Arrays; 8 | 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | 17 | public class StatusCodeVerifier { 18 | 19 | int expectedStatusCode; 20 | int[] expectedStatusCodes; 21 | String expectedStatusCodeRegex; 22 | StatusCodeVerifierStrategy statusCodeVerifierStrategy; 23 | 24 | public StatusCodeVerifier(int expectedStatusCode) throws Exception { 25 | verifyStatusCodesCompliance(new int[]{expectedStatusCode}); 26 | this.expectedStatusCode = expectedStatusCode; 27 | this.statusCodeVerifierStrategy = StatusCodeVerifierStrategy.EXPECTED_STATUS_CODE; 28 | } 29 | 30 | public StatusCodeVerifier(int[] expectedStatusCodes) throws Exception { 31 | verifyStatusCodesCompliance(expectedStatusCodes); 32 | this.expectedStatusCodes = expectedStatusCodes; 33 | this.statusCodeVerifierStrategy = StatusCodeVerifierStrategy.LIST_OF_POSSIBLE_STATUS_CODES; 34 | } 35 | 36 | public StatusCodeVerifier(String regexForPossibleStatusCodes) throws Exception { 37 | if (regexForPossibleStatusCodes == null || regexForPossibleStatusCodes.isEmpty()) { 38 | throw new Exception("The regex must be filled"); 39 | } 40 | this.expectedStatusCodeRegex = regexForPossibleStatusCodes; 41 | this.statusCodeVerifierStrategy = StatusCodeVerifierStrategy.REGEX_FOR_POSSIBLE_STATUS_CODES; 42 | } 43 | 44 | public void verifyStatusCode(int httpStatusCode) throws Exception { 45 | verifyStatusCode(httpStatusCode, false); 46 | } 47 | 48 | public void verifyStatusCode(int httpStatusCode, Boolean useAssertions) throws Exception { 49 | switch (this.statusCodeVerifierStrategy) { 50 | case EXPECTED_STATUS_CODE: 51 | if (this.expectedStatusCode != httpStatusCode) { 52 | statusCodeCheckFailed(String.format("The status code %s didn't match: %s", httpStatusCode, this.expectedStatusCode), useAssertions); 53 | } 54 | break; 55 | case LIST_OF_POSSIBLE_STATUS_CODES: 56 | boolean hasMatch = false; 57 | for (int statusCode : this.expectedStatusCodes) { 58 | if (statusCode == httpStatusCode) { 59 | hasMatch = true; 60 | break; 61 | } 62 | } 63 | if (!hasMatch) { 64 | statusCodeCheckFailed(String.format("The status code %s didn't match any: %s", httpStatusCode, Arrays.toString(this.expectedStatusCodes)), useAssertions); 65 | } 66 | break; 67 | case REGEX_FOR_POSSIBLE_STATUS_CODES: 68 | if (!RegexHelper.isMatch(this.expectedStatusCodeRegex, Integer.toString(httpStatusCode))) { 69 | statusCodeCheckFailed(String.format("The status code %s didn't match the provided regex: %s", httpStatusCode, this.expectedStatusCodeRegex), useAssertions); 70 | } 71 | break; 72 | default: 73 | throw new Exception(String.format("The status code strategy [%s] is not supported!", this.statusCodeVerifierStrategy.toString())); 74 | } 75 | } 76 | 77 | private void verifyStatusCodesCompliance(int[] possibleStatusCodes) throws Exception { 78 | if (possibleStatusCodes == null || possibleStatusCodes.length == 0) { 79 | throw new Exception("You must provide what is\\are the expected status code(s)!!!"); 80 | } 81 | 82 | for (int statusCode : possibleStatusCodes) { 83 | String statusTemp = Integer.toString(statusCode); 84 | if (!RegexHelper.isMatch("[1-5][0-9][0-9]", statusTemp)) { 85 | throw new Exception(String.format("The status code %s does not match the possible HTTP status code spec!!!", statusTemp)); 86 | } 87 | } 88 | } 89 | 90 | private void statusCodeCheckFailed(String msg, boolean useAssertions) throws Exception { 91 | if (useAssertions) { 92 | Assert.fail(msg); 93 | } else { 94 | throw new Exception(msg); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/base/HttpClientTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | import com.github.jeansantos38.stf.dataclasses.web.proxy.ProxySettings; 4 | import com.github.jeansantos38.stf.framework.httpclient.HttpClient; 5 | import com.github.jeansantos38.stf.framework.logger.TestLog; 6 | import org.testng.annotations.BeforeClass; 7 | 8 | public class HttpClientTestBase extends WireMockTestBase { 9 | 10 | protected HttpClient httpClient; 11 | 12 | @BeforeClass 13 | public void initializeWebdriver() throws Exception { 14 | ProxySettings proxySettings = new ProxySettings(true); 15 | httpClient = new HttpClient(new TestLog(), proxySettings); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/base/MainTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 6 | import org.testng.annotations.BeforeClass; 7 | import org.testng.annotations.Optional; 8 | import org.testng.annotations.Parameters; 9 | 10 | public class MainTestBase { 11 | 12 | protected static TestLog testLog; 13 | protected WaitHelper waitHelper; 14 | 15 | 16 | @BeforeClass 17 | @Parameters({"optionalGlobalParameterExample"}) 18 | public void mainTestBaseInitialize(@Optional("") String param1) throws Exception { 19 | testLog = new TestLog(true); 20 | testLog.logIt("Parameter value provided from testRunConfig:" + param1); 21 | waitHelper = new WaitHelper(); 22 | } 23 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/base/WireMockTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import org.testng.annotations.AfterClass; 5 | import org.testng.annotations.BeforeClass; 6 | 7 | import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; 8 | 9 | public class WireMockTestBase extends MainTestBase { 10 | 11 | protected Integer wiremockPort = 7654; 12 | protected WireMockServer wireMockServer; 13 | protected String baseServerUrl; 14 | 15 | @BeforeClass 16 | public void initializeMockServer() { 17 | wireMockServer = new WireMockServer(options().port(wiremockPort)); 18 | wireMockServer.start(); 19 | baseServerUrl = String.format("http://127.0.0.1:%s", wiremockPort); 20 | } 21 | 22 | @AfterClass 23 | public void endMockServer() { 24 | if (wireMockServer != null && wireMockServer.isRunning()) { 25 | wireMockServer.stop(); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/pojo/Bicycle.java: -------------------------------------------------------------------------------- 1 | package system.test.pojo; 2 | 3 | public class Bicycle { 4 | 5 | public String color; 6 | 7 | public String price; 8 | 9 | public Bicycle() { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/pojo/Book.java: -------------------------------------------------------------------------------- 1 | package system.test.pojo; 2 | 3 | public class Book { 4 | 5 | public String author; 6 | 7 | public String price; 8 | 9 | public String category; 10 | 11 | public String title; 12 | 13 | public String isbn; 14 | 15 | public Book() { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/pojo/BooksStore.java: -------------------------------------------------------------------------------- 1 | package system.test.pojo; 2 | 3 | public class BooksStore { 4 | 5 | public Store store; 6 | 7 | public String expensive; 8 | 9 | public BooksStore() { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/pojo/CommonPayloadBody.java: -------------------------------------------------------------------------------- 1 | package system.test.pojo; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.github.jeansantos38.stf.framework.serialization.SerializeHelper; 6 | 7 | public class CommonPayloadBody { 8 | 9 | public String id; 10 | public String msg; 11 | public String value; 12 | 13 | public CommonPayloadBody() { 14 | } 15 | 16 | public CommonPayloadBody(String id, String msg, String value) { 17 | this.id = id; 18 | this.msg = msg; 19 | this.value = value; 20 | } 21 | 22 | 23 | public String serializeContent() throws JsonProcessingException { 24 | return SerializeHelper.serializeJsonObject(this, JsonInclude.Include.NON_NULL); 25 | } 26 | 27 | public byte[] extractBytes() throws JsonProcessingException { 28 | return serializeContent().getBytes(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/pojo/Store.java: -------------------------------------------------------------------------------- 1 | package system.test.pojo; 2 | 3 | public class Store { 4 | 5 | public Bicycle bicycle; 6 | 7 | public Book[] book; 8 | 9 | public Store() { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/BuiltInAssertionsTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedHeader; 4 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedResponse; 5 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 6 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 7 | import com.github.tomakehurst.wiremock.WireMockServer; 8 | import io.qameta.allure.Description; 9 | import org.testng.Assert; 10 | import org.testng.annotations.BeforeClass; 11 | import org.testng.annotations.Test; 12 | import system.test.base.HttpClientTestBase; 13 | import system.test.pojo.CommonPayloadBody; 14 | 15 | import java.io.File; 16 | import java.io.IOException; 17 | 18 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 19 | 20 | public class BuiltInAssertionsTests extends HttpClientTestBase { 21 | 22 | CommonPayloadBody requestBody; 23 | byte[] responseBodyToBeUsedByMock; 24 | String endpoint; 25 | String url; 26 | HttpDetailedHeader httpDetailedHeader = new HttpDetailedHeader("stf", "qa"); 27 | 28 | @BeforeClass 29 | public void initializeMocks() throws IOException { 30 | 31 | requestBody = new CommonPayloadBody( 32 | "123", 33 | "hi this is a msg from request", 34 | "abc123"); 35 | 36 | responseBodyToBeUsedByMock = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("responseBooksStore.json")).getBytes(); 37 | endpoint = "/deserialize/some/bookstore"; 38 | url = baseServerUrl + endpoint; 39 | configureStub(wireMockServer, responseBodyToBeUsedByMock, endpoint); 40 | } 41 | 42 | @Test 43 | @Description("Happy path test. Using built in assertions!") 44 | public void builtInAssertionsTest() throws Exception { 45 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 46 | .assertExpectedStatusCode(200) 47 | .assertResponseElapsedTimeInMs(2000) 48 | .assertResponseContainsHeader("Content-Type", "text/plain") 49 | .assertResponseContainsHeader("Matched-Stub-Id") 50 | .assertResponseBodyContainsText("The Lord of the Rings") 51 | .assertJsonPathFromResponse(HttpDetailedResponse.Operator.EQUAL, "$['store']['book'][3]['title']", "The Lord of the Rings"); 52 | } 53 | 54 | @Test 55 | @Description("Happy path test! A bit more verbose mode.") 56 | public void builtInAssertionsVariation2Test() throws Exception { 57 | HttpDetailedResponse httpDetailedResponse = httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()); 58 | httpDetailedResponse.assertExpectedStatusCode(200); 59 | httpDetailedResponse.assertResponseElapsedTimeInMs(2000); 60 | httpDetailedResponse.assertResponseContainsHeader("Content-Type", "text/plain"); 61 | httpDetailedResponse.assertResponseContainsHeader("Matched-Stub-Id"); 62 | httpDetailedResponse.assertResponseBodyContainsText("The Lord of the Rings"); 63 | httpDetailedResponse.assertJsonPathFromResponse(HttpDetailedResponse.Operator.EQUAL, "$['store']['book'][3]['title']", "The Lord of the Rings"); 64 | } 65 | 66 | @Test 67 | @Description("Not so happy path test!") 68 | public void builtInAssertionsConstraintsTest() throws Exception { 69 | HttpDetailedResponse httpDetailedResponse = httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()); 70 | try { 71 | httpDetailedResponse.assertExpectedStatusCode(500); 72 | } catch (AssertionError e) { 73 | Assert.assertEquals("The status code 200 didn't match: 500", e.getMessage()); 74 | } 75 | try { 76 | httpDetailedResponse.assertResponseElapsedTimeInMs(2); 77 | } catch (AssertionError e) { 78 | Assert.assertTrue(e.getMessage().contains("instead 2 ms expected")); 79 | } 80 | try { 81 | httpDetailedResponse.assertResponseContainsHeader("Content-Type", "xml/plain"); 82 | } catch (AssertionError e) { 83 | Assert.assertEquals("The header {Content-Type:xml/plain} was not found in response! expected [true] but found [false]", e.getMessage()); 84 | } 85 | try { 86 | httpDetailedResponse.assertResponseContainsHeader("Matched-Stub-Id-blah"); 87 | } catch (AssertionError e) { 88 | Assert.assertEquals("The header [Matched-Stub-Id-blah] was not found in response! expected [true] but found [false]", e.getMessage()); 89 | } 90 | try { 91 | httpDetailedResponse.assertResponseBodyContainsText("Blah Blah"); 92 | } catch (AssertionError e) { 93 | Assert.assertEquals("The payload response does not contains: Blah Blah expected [true] but found [false]", e.getMessage()); 94 | } 95 | try { 96 | httpDetailedResponse.assertJsonPathFromResponse(HttpDetailedResponse.Operator.EQUAL, "$['store']['book'][2]['title']", "The Lord of the Rings"); 97 | } catch (AssertionError e) { 98 | Assert.assertEquals("expected [The Lord of the Rings] but found [Moby Dick]", e.getMessage()); 99 | } 100 | } 101 | 102 | private void configureStub(WireMockServer wireMockServer, byte[] responseBody, String endpoint) { 103 | wireMockServer.stubFor(any(urlEqualTo(endpoint)) 104 | .withHeader("stf", containing("qa")) 105 | .willReturn(aResponse() 106 | .withStatus(200) 107 | .withHeader("Content-Type", "text/plain") 108 | .withBody(responseBody))); 109 | } 110 | 111 | private String discoverAbsoluteFilePath(String filename) { 112 | return new File(String.format("src/test/resources/%s", filename)).getAbsolutePath(); 113 | } 114 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/DemoParallelTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedHeader; 4 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 5 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 6 | import com.github.tomakehurst.wiremock.WireMockServer; 7 | import io.qameta.allure.Description; 8 | import org.testng.annotations.BeforeClass; 9 | import org.testng.annotations.Test; 10 | import system.test.base.HttpClientTestBase; 11 | import system.test.pojo.CommonPayloadBody; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | 16 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 17 | 18 | public class DemoParallelTests extends HttpClientTestBase { 19 | 20 | CommonPayloadBody requestBody; 21 | byte[] responseBodyToBeUsedByMock; 22 | String endpoint; 23 | String url; 24 | HttpDetailedHeader httpDetailedHeader = new HttpDetailedHeader("stf", "qa"); 25 | 26 | @BeforeClass 27 | public void initializeMocks() throws IOException { 28 | 29 | requestBody = new CommonPayloadBody( 30 | "123", 31 | "hi this is a msg from request", 32 | "abc123"); 33 | 34 | responseBodyToBeUsedByMock = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("responseBooksStore.json")).getBytes(); 35 | endpoint = "/deserialize/some/bookstore"; 36 | url = baseServerUrl + endpoint; 37 | configureStub(wireMockServer, responseBodyToBeUsedByMock, endpoint); 38 | } 39 | 40 | @Test 41 | @Description("A simple rest test.") 42 | public void simpleTest1() throws Exception { 43 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 44 | .assertExpectedStatusCode(200) 45 | .assertResponseElapsedTimeInMs(7000); 46 | } 47 | 48 | @Test 49 | @Description("A simple rest test.") 50 | public void simpleTest2() throws Exception { 51 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 52 | .assertExpectedStatusCode(200) 53 | .assertResponseElapsedTimeInMs(7000); 54 | } 55 | 56 | @Test 57 | @Description("A simple rest test.") 58 | public void simpleTest3() throws Exception { 59 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 60 | .assertExpectedStatusCode(200) 61 | .assertResponseElapsedTimeInMs(7000); 62 | } 63 | 64 | @Test 65 | @Description("A simple rest test.") 66 | public void simpleTest4() throws Exception { 67 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 68 | .assertExpectedStatusCode(200) 69 | .assertResponseElapsedTimeInMs(7000); 70 | } 71 | 72 | @Test 73 | @Description("A simple rest test.") 74 | public void simpleTest5() throws Exception { 75 | httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody.extractBytes()) 76 | .assertExpectedStatusCode(200) 77 | .assertResponseElapsedTimeInMs(7000); 78 | } 79 | 80 | 81 | private void configureStub(WireMockServer wireMockServer, byte[] responseBody, String endpoint) { 82 | wireMockServer.stubFor(any(urlEqualTo(endpoint)) 83 | .withHeader("stf", containing("qa")) 84 | .willReturn(aResponse() 85 | .withLogNormalRandomDelay(5000, 0.1) 86 | .withStatus(200) 87 | .withHeader("Content-Type", "text/plain") 88 | .withBody(responseBody))); 89 | } 90 | 91 | private String discoverAbsoluteFilePath(String filename) { 92 | return new File(String.format("src/test/resources/%s", filename)).getAbsolutePath(); 93 | } 94 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/DeserializeResponseTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.github.tomakehurst.wiremock.WireMockServer; 5 | import com.jayway.jsonpath.JsonPath; 6 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedRequest; 7 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedResponse; 8 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 9 | import com.github.jeansantos38.stf.enums.serialization.SerializationType; 10 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 11 | import com.github.jeansantos38.stf.framework.serialization.DeserializeHelper; 12 | import io.qameta.allure.*; 13 | import org.testng.Assert; 14 | import org.testng.annotations.BeforeClass; 15 | import org.testng.annotations.Test; 16 | import system.test.base.HttpClientTestBase; 17 | import system.test.pojo.CommonPayloadBody; 18 | 19 | import java.io.File; 20 | 21 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 22 | 23 | public class DeserializeResponseTests extends HttpClientTestBase { 24 | 25 | CommonPayloadBody requestBody; 26 | CommonPayloadBody responseBodyToBeUsedByMock; 27 | String endpoint; 28 | 29 | @BeforeClass 30 | public void initializeMocks() throws JsonProcessingException { 31 | 32 | requestBody = new CommonPayloadBody( 33 | "123", 34 | "hi this is a msg from request", 35 | "abc123"); 36 | 37 | responseBodyToBeUsedByMock = new CommonPayloadBody( 38 | "321", 39 | "hi this is a msg from response", 40 | "xyz098"); 41 | 42 | endpoint = "/deserialize/some/thing"; 43 | 44 | configureStub(wireMockServer, responseBodyToBeUsedByMock.extractBytes(), endpoint); 45 | } 46 | 47 | @Test 48 | @Severity(SeverityLevel.BLOCKER) 49 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 50 | @Description("Perform a http request, then deserialize it into a POJO") 51 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 52 | public void deserializeUsingPOJO() throws Exception { 53 | 54 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 55 | httpDetailedRequest.url = baseServerUrl + endpoint; 56 | httpDetailedRequest.method = HttpRequestMethod.POST; 57 | httpDetailedRequest.payloadToBeSent = requestBody.extractBytes(); 58 | 59 | HttpDetailedResponse httpResponse = httpClient.performHttpRequest(httpDetailedRequest); 60 | 61 | Assert.assertEquals(httpResponse.statusCode, 201); 62 | 63 | CommonPayloadBody deserializedResponse = DeserializeHelper.deserializeStringToObject(CommonPayloadBody.class, SerializationType.JSON, httpResponse.responseBody); 64 | 65 | Assert.assertEquals(deserializedResponse.msg, responseBodyToBeUsedByMock.msg); 66 | Assert.assertEquals(deserializedResponse.id, responseBodyToBeUsedByMock.id); 67 | Assert.assertEquals(deserializedResponse.value, responseBodyToBeUsedByMock.value); 68 | } 69 | 70 | @Test 71 | @Severity(SeverityLevel.BLOCKER) 72 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 73 | @Description("Perform a http request, then deserialize it into a string using JsonPath API") 74 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 75 | public void deserializeUsingJsonPathParser() throws Exception { 76 | 77 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 78 | httpDetailedRequest.url = baseServerUrl + endpoint; 79 | httpDetailedRequest.method = HttpRequestMethod.POST; 80 | httpDetailedRequest.payloadToBeSent = requestBody.extractBytes(); 81 | 82 | HttpDetailedResponse httpResponse = httpClient.performHttpRequest(httpDetailedRequest); 83 | 84 | Assert.assertEquals(httpResponse.statusCode, 201); 85 | 86 | Assert.assertEquals(JsonPath.parse(httpResponse.responseBody).read("$.msg"), responseBodyToBeUsedByMock.msg); 87 | Assert.assertEquals(JsonPath.parse(httpResponse.responseBody).read("$.id"), responseBodyToBeUsedByMock.id); 88 | Assert.assertEquals(JsonPath.parse(httpResponse.responseBody).read("$.value"), responseBodyToBeUsedByMock.value); 89 | } 90 | 91 | @Test 92 | @Severity(SeverityLevel.BLOCKER) 93 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 94 | @Description("Perform a http request reading body content and expected values from files in hard disk") 95 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 96 | public void readRequestAndResponseFromDisk() throws Exception { 97 | 98 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 99 | httpDetailedRequest.url = baseServerUrl + endpoint; 100 | httpDetailedRequest.method = HttpRequestMethod.POST; 101 | httpDetailedRequest.payloadToBeSent = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("requestBody.json")).getBytes(); 102 | 103 | HttpDetailedResponse httpResponse = httpClient.performHttpRequest(httpDetailedRequest); 104 | 105 | Assert.assertEquals(httpResponse.statusCode, 201); 106 | 107 | String expectedResponseFromDisk = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("responseBody.json")); 108 | Assert.assertTrue(expectedResponseFromDisk.contains(JsonPath.parse(httpResponse.responseBody).read("$.msg"))); 109 | Assert.assertTrue(expectedResponseFromDisk.contains(JsonPath.parse(httpResponse.responseBody).read("$.id"))); 110 | Assert.assertTrue(expectedResponseFromDisk.contains(JsonPath.parse(httpResponse.responseBody).read("$.value"))); 111 | } 112 | 113 | private void configureStub(WireMockServer wireMockServer, byte[] responseBody, String endpoint) { 114 | wireMockServer.stubFor(any(urlEqualTo(endpoint)) 115 | .willReturn(aResponse() 116 | .withStatus(201) 117 | .withHeader("Content-Type", "text/plain") 118 | .withBody(responseBody))); 119 | } 120 | 121 | private String discoverAbsoluteFilePath(String filename) { 122 | return new File(String.format("src/test/resources/%s", filename)).getAbsolutePath(); 123 | } 124 | 125 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/HttpDetailedRequestTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedRequest; 5 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedResponse; 6 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 7 | import io.qameta.allure.*; 8 | import org.testng.Assert; 9 | import org.testng.annotations.Test; 10 | import system.test.base.HttpClientTestBase; 11 | import system.test.pojo.CommonPayloadBody; 12 | 13 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 14 | 15 | public class HttpDetailedRequestTests extends HttpClientTestBase { 16 | 17 | @Test 18 | @Severity(SeverityLevel.BLOCKER) 19 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 20 | @Description("Perform a HTTP request using HTTP Detailed request object and a string as payload body") 21 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 22 | public void detailedRequestTest() throws Exception { 23 | String responseBody = "Hello STF user! Testing PUT with payload!"; 24 | String endpoint = "/put/some/thing"; 25 | String requestBody = "{ \"id\":\"12345\" }"; 26 | configureStubForPutWithBody(wireMockServer, requestBody.getBytes(), responseBody.getBytes(), endpoint); 27 | 28 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 29 | httpDetailedRequest.url = baseServerUrl + endpoint; 30 | httpDetailedRequest.method = HttpRequestMethod.PUT; 31 | httpDetailedRequest.payloadToBeSent = requestBody.getBytes(); 32 | 33 | 34 | HttpDetailedResponse httpResponse = httpClient.performHttpRequest(httpDetailedRequest); 35 | 36 | Assert.assertEquals(httpResponse.statusCode, 200); 37 | Assert.assertEquals(httpResponse.responseBody, responseBody); 38 | } 39 | 40 | @Test 41 | @Severity(SeverityLevel.BLOCKER) 42 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 43 | @Description("Perform a HTTP request using HTTP Detailed request object and a POJO as payload body") 44 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 45 | public void putRequestWithPayloadUsingObject() throws Exception { 46 | 47 | CommonPayloadBody requestBody = new CommonPayloadBody( 48 | "123", 49 | "hi this is a msg from request", 50 | "abc123"); 51 | 52 | CommonPayloadBody responseBody = new CommonPayloadBody( 53 | "321", 54 | "hi this is a msg from response", 55 | "xyz098"); 56 | 57 | String endpoint = "/get/some/thing"; 58 | configureStubForPutWithBody(wireMockServer, requestBody.extractBytes(), responseBody.extractBytes(), endpoint); 59 | 60 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 61 | httpDetailedRequest.url = baseServerUrl + endpoint; 62 | httpDetailedRequest.method = HttpRequestMethod.PUT; 63 | httpDetailedRequest.payloadToBeSent = requestBody.extractBytes(); 64 | 65 | HttpDetailedResponse httpResponse = httpClient.performHttpRequest(httpDetailedRequest); 66 | 67 | Assert.assertEquals(httpResponse.statusCode, 200); 68 | Assert.assertTrue(httpResponse.responseBody.contains(responseBody.msg)); 69 | } 70 | 71 | private void configureStubForPutWithBody(WireMockServer wireMockServer, byte[] requestBody, byte[] responseBody, String endpoint) { 72 | wireMockServer.stubFor(put(urlEqualTo(endpoint)).withRequestBody(binaryEqualTo(requestBody)) 73 | .willReturn(aResponse() 74 | .withStatus(200) 75 | .withHeader("Content-Type", "text/plain") 76 | .withBody(responseBody))); 77 | } 78 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/HttpLoggerTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedHeader; 5 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedHeaders; 6 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedRequest; 7 | import com.github.jeansantos38.stf.enums.http.HttpRequestLogLevel; 8 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 9 | import io.qameta.allure.*; 10 | import org.testng.annotations.Test; 11 | import system.test.base.HttpClientTestBase; 12 | 13 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 14 | 15 | public class HttpLoggerTests extends HttpClientTestBase { 16 | 17 | @Test 18 | @Severity(SeverityLevel.BLOCKER) 19 | @Story("A QA should be capable of easily creating HTTP request to REST APIs") 20 | @Description("Perform a http request using new headers object") 21 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 22 | public void testingLogger() throws Exception { 23 | //Configuring mock 24 | String endpoint = "/put/some/thing/new"; 25 | configureStubForGetRequestWithNewHeaders(wireMockServer, endpoint); 26 | 27 | //configuring http request 28 | HttpDetailedHeader httpDetailedRequestHeader1 = new HttpDetailedHeader("request -> super secret header key", "request -> super secret request value"); 29 | HttpDetailedHeaders httpDetailedHeaders = new HttpDetailedHeaders(); 30 | httpDetailedHeaders.headerList.add(httpDetailedRequestHeader1); 31 | 32 | HttpDetailedRequest httpDetailedRequest = new HttpDetailedRequest(); 33 | httpDetailedRequest.headers = httpDetailedHeaders; 34 | httpDetailedRequest.url = baseServerUrl + endpoint; 35 | httpDetailedRequest.method = HttpRequestMethod.PUT; 36 | httpDetailedRequest.payloadToBeSent = "{ super secret request body content}".getBytes(); 37 | 38 | //executing the request 39 | for (HttpRequestLogLevel httpRequestLogLevel : HttpRequestLogLevel.values()) { 40 | testLog.logIt(String.format("\n\n###### Start of log check for %s", httpRequestLogLevel)); 41 | testLog.logIt(String.format("\n\nThis is the log result from %s", httpRequestLogLevel)); 42 | httpDetailedRequest.logLevel = httpRequestLogLevel; 43 | httpClient.performHttpRequest(httpDetailedRequest); 44 | testLog.logIt(String.format("\n\n###### End of log check for %s", httpRequestLogLevel)); 45 | } 46 | } 47 | 48 | private void configureStubForGetRequestWithNewHeaders(WireMockServer wireMockServer, String endpoint) { 49 | wireMockServer.stubFor(any(urlEqualTo(endpoint)) 50 | .willReturn(aResponse() 51 | .withStatus(200) 52 | .withHeader("Content-Type", "text/plain") 53 | .withHeader("response -> super secret header key", "response -> super secret header value") 54 | .withBody("{top secret response body content!}") 55 | )); 56 | } 57 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/java/system/test/rest/ResponseParsingTests.java: -------------------------------------------------------------------------------- 1 | package system.test.rest; 2 | 3 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedHeader; 4 | import com.github.jeansantos38.stf.dataclasses.web.http.HttpDetailedResponse; 5 | import com.github.jeansantos38.stf.enums.http.HttpRequestMethod; 6 | import com.github.jeansantos38.stf.enums.serialization.SerializationType; 7 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 8 | import com.github.tomakehurst.wiremock.WireMockServer; 9 | import io.qameta.allure.Description; 10 | import net.minidev.json.JSONArray; 11 | import org.testng.Assert; 12 | import org.testng.annotations.BeforeClass; 13 | import org.testng.annotations.Test; 14 | import system.test.base.HttpClientTestBase; 15 | import system.test.pojo.BooksStore; 16 | 17 | 18 | import java.io.File; 19 | import java.io.IOException; 20 | 21 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 22 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; 23 | 24 | public class ResponseParsingTests extends HttpClientTestBase { 25 | 26 | byte[] requestBody; 27 | byte[] responsePayload; 28 | String endpoint; 29 | String url; 30 | HttpDetailedHeader httpDetailedHeader = new HttpDetailedHeader("stf", "qa"); 31 | 32 | @BeforeClass 33 | public void initializeMocks() throws IOException { 34 | requestBody = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("requestBody.json")).getBytes(); 35 | responsePayload = InputOutputHelper.readContentFromFile(discoverAbsoluteFilePath("responseBooksStore.json")).getBytes(); 36 | endpoint = "/deserialize/some/bookstore2"; 37 | url = baseServerUrl + endpoint; 38 | configureStub(wireMockServer, responsePayload, endpoint); 39 | } 40 | 41 | @Test 42 | @Description("Deserialize response using fasterxml api.") 43 | public void deserializeToPojoTest1() throws Exception { 44 | HttpDetailedResponse httpDetailedResponse = httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody); 45 | httpDetailedResponse.assertExpectedStatusCode(200); 46 | BooksStore booksStore = httpDetailedResponse.deserializeResponseBodyToObject(BooksStore.class, SerializationType.JSON); 47 | Assert.assertEquals(booksStore.store.book[3].author, "J. R. R. Tolkien"); 48 | Assert.assertEquals(booksStore.store.book[3].title, "The Lord of the Rings"); 49 | Assert.assertEquals(booksStore.store.book[3].isbn, "0-395-19395-8"); 50 | //or 51 | httpDetailedResponse.assertJsonPathFromResponse(HttpDetailedResponse.Operator.EQUAL, "$['store']['book'][3]['isbn']", "0-395-19395-8"); 52 | } 53 | 54 | 55 | @Test 56 | @Description("Deserialize response using jsonPath api.") 57 | public void readJsonPathFromResponseTest1() throws Exception { 58 | HttpDetailedResponse httpDetailedResponse = httpClient.performHttpRequest(HttpRequestMethod.POST, url, httpDetailedHeader, requestBody); 59 | httpDetailedResponse.assertExpectedStatusCode(200); 60 | JSONArray author = httpDetailedResponse.readJsonPathFromResponse("$['store']['book'][3]['author']"); 61 | JSONArray title = httpDetailedResponse.readJsonPathFromResponse("$['store']['book'][3]['title']"); 62 | JSONArray isbn = httpDetailedResponse.readJsonPathFromResponse("$['store']['book'][3]['isbn']"); 63 | Assert.assertEquals(author.get(0), "J. R. R. Tolkien"); 64 | Assert.assertEquals(title.get(0), "The Lord of the Rings"); 65 | Assert.assertEquals(isbn.get(0), "0-395-19395-8"); 66 | //or 67 | httpDetailedResponse.assertJsonPathFromResponse(HttpDetailedResponse.Operator.EQUAL, "$['store']['book'][3]['title']", "The Lord of the Rings"); 68 | } 69 | 70 | private void configureStub(WireMockServer wireMockServer, byte[] responseBody, String endpoint) { 71 | wireMockServer.stubFor(any(urlEqualTo(endpoint)) 72 | .withHeader("stf", containing("qa")) 73 | .willReturn(aResponse() 74 | .withLogNormalRandomDelay(5000, 0.1) 75 | .withStatus(200) 76 | .withHeader("Content-Type", "text/plain") 77 | .withBody(responseBody))); 78 | } 79 | 80 | private String discoverAbsoluteFilePath(String filename) { 81 | return new File(String.format("src/test/resources/%s", filename)).getAbsolutePath(); 82 | } 83 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/resources/requestBody.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "123", 3 | "msg": "hi this is a msg from request", 4 | "value": "abc123" 5 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/resources/responseBody.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "321", 3 | "msg": "hi this is a msg from response", 4 | "value": "xyz098" 5 | } -------------------------------------------------------------------------------- /stf-http-client-lib/src/test/resources/responseBooksStore.json: -------------------------------------------------------------------------------- 1 | { 2 | "store": { 3 | "book": [ 4 | { 5 | "category": "reference", 6 | "author": "Nigel Rees", 7 | "title": "Sayings of the Century", 8 | "price": 8.95 9 | }, 10 | { 11 | "category": "fiction", 12 | "author": "Evelyn Waugh", 13 | "title": "Sword of Honour", 14 | "price": 12.99 15 | }, 16 | { 17 | "category": "fiction", 18 | "author": "Herman Melville", 19 | "title": "Moby Dick", 20 | "isbn": "0-553-21311-3", 21 | "price": 8.99 22 | }, 23 | { 24 | "category": "fiction", 25 | "author": "J. R. R. Tolkien", 26 | "title": "The Lord of the Rings", 27 | "isbn": "0-395-19395-8", 28 | "price": 22.99 29 | } 30 | ], 31 | "bicycle": { 32 | "color": "red", 33 | "price": 19.95 34 | } 35 | }, 36 | "expensive": 10 37 | } -------------------------------------------------------------------------------- /stf-http-client-lib/testRunConfig/testRunConfig_http-client_rest_demo-tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /stf-http-client-lib/testRunConfig/testRunConfig_http-client_thread-mlt_tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /stf-http-client-lib/testRunConfig/testRunConfig_http-client_thread-single_tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /stf-misc-lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | com.github.jeansantos38.stf 8 | smart-test-framework 9 | 1.3-SNAPSHOT 10 | 11 | 4.0.0 12 | 13 | stf-misc 14 | 1.3.1-SNAPSHOT 15 | jar 16 | STF-Miscellaneous 17 | https://github.com/HPInc/smart-test-framework 18 | 19 | 20 | 2.14.0 21 | 22 | 23 | 24 | 25 | 26 | org.jsoup 27 | jsoup 28 | 1.15.3 29 | 30 | 31 | com.fasterxml.jackson.dataformat 32 | jackson-dataformat-xml 33 | ${jackson.version} 34 | 35 | 36 | 37 | com.fasterxml.jackson.core 38 | jackson-databind 39 | ${jackson.version} 40 | 41 | 42 | 43 | com.fasterxml.jackson.dataformat 44 | jackson-dataformat-yaml 45 | ${jackson.version} 46 | 47 | 48 | org.json 49 | json 50 | 20230227 51 | 52 | 53 | 54 | commons-lang 55 | commons-lang 56 | 2.4 57 | 58 | 59 | 60 | commons-io 61 | commons-io 62 | 2.7 63 | compile 64 | 65 | 66 | com.jayway.jsonpath 67 | json-path 68 | 2.5.0 69 | 70 | 71 | 72 | 73 | 74 | 75 | org.apache.maven.plugins 76 | maven-surefire-plugin 77 | ${maven.surefire.plugin.version} 78 | 79 | 80 | testRunConfig/testRunConfig_misc-tests.xml 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/datadriven/DataDriven.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.datadriven; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public class DataDriven { 10 | public SmartDataDriven[] SmartDataDriven; 11 | 12 | public DataDriven() { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/datadriven/SmartDataDriven.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.datadriven; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public class SmartDataDriven { 10 | 11 | public String instructionSet; 12 | public Statements[] statements; 13 | 14 | public SmartDataDriven() { 15 | } 16 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/datadriven/Statement.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.datadriven; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | /************************************************************ 6 | * © Copyright 2019 HP Development Company, L.P. 7 | * SPDX-License-Identifier: MIT 8 | * 9 | * Smart Test Framework 10 | ************************************************************/ 11 | @JsonIgnoreProperties(ignoreUnknown = true) 12 | public class Statement { 13 | 14 | public String agent; //sikuli, appium, selenium 15 | public String purpose; //set, assert 16 | public String selector; //The selector unique id (99% of the cases) 17 | public String locator; //The locator mechanism for the selector. It's not required for Sikuli. 18 | public String method; //What will be the method used by sikuli to execute a action. It's not required for WebDrivers. 19 | public String innerSelector; //The selector unique id of a web element inside a main web element (combo-boxes of AngularJS). 20 | public String innerLocator; 21 | public Object delayActionInMs; //Time to wait before executing the statement. 22 | public String areaId; //Applicable only for Sikuli. It says what is the navigator area id to look for. 23 | public String action; //The action and the target type (usually setField for Web Driver usage, or (99% of the cases), but it could be setWhatever -> that could be a new type of field or specific method.) 24 | public String innerActionType; //The action and selector type of a web element hidden inside a main web element (combo-boxes of AngularJS). 25 | public String contentType; //string, int, double, etc. 26 | public String operator; //AssertTrue, Exists, False, Equals, NotNull, etc. 27 | public Object[] content; //The value to be set or asserted. 28 | public String contentModifier; //stringFormat, generateRandom, sortValueFromArray (just one value to be replaced). 29 | public String randomValueCompositionForContent; //numeric, alphabetic, alphaNumeric 30 | public int randomValueMaxLengthForContent; //1-n 31 | public int xCoordinate; 32 | public int yCoordinate; 33 | public int rectangleTopLeftX; 34 | public int rectangleTopLeftY; 35 | public int rectangleBottomRightX; 36 | public int rectangleBottomRightY; 37 | 38 | public Statement() { 39 | } 40 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/dataclasses/datadriven/Statements.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.dataclasses.datadriven; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public class Statements { 10 | 11 | public Statement statement; 12 | 13 | public Statements() { 14 | } 15 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/enums/serialization/SerializationType.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.serialization; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum SerializationType { 10 | JSON, XML, YAML 11 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/enums/wait/ThreadWait.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.wait; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum ThreadWait { 10 | WAIT_1_SEC, WAIT_2_SEC, WAIT_3_SEC, WAIT_5_SEC, WAIT_10_SEC, WAIT_15_SEC, WAIT_30_SEC, WAIT_45_SEC, WAIT_60_SEC, WAIT_2_MIN, WAIT_3_MIN, WAIT_5_MIN, WAIT_10_MIN 11 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/logger/TestLog.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.logger; 2 | 3 | import java.util.List; 4 | import java.util.logging.ConsoleHandler; 5 | import java.util.logging.Handler; 6 | import java.util.logging.Level; 7 | import java.util.logging.Logger; 8 | 9 | /************************************************************ 10 | * © Copyright 2019 HP Development Company, L.P. 11 | * SPDX-License-Identifier: MIT 12 | * 13 | * Smart Test Framework 14 | ************************************************************/ 15 | public class TestLog { 16 | 17 | private static final String LOGGER_STRING_NAME = "TestLog"; 18 | 19 | private Logger testLog; 20 | private boolean enableLog; 21 | 22 | /*** 23 | * Constructor 24 | */ 25 | public TestLog() { 26 | this(true); 27 | } 28 | 29 | /*** 30 | * Constructor 31 | * @param enableLogs: Enable logs or not. 32 | */ 33 | public TestLog(boolean enableLogs) { 34 | this.enableLog = enableLogs; 35 | this.testLog = Logger.getLogger(LOGGER_STRING_NAME); 36 | Handler handlerObj = new ConsoleHandler(); 37 | handlerObj.setLevel(Level.ALL); 38 | testLog.addHandler(handlerObj); 39 | testLog.setLevel(Level.ALL); 40 | testLog.setUseParentHandlers(false); 41 | this.enableLog = true; 42 | } 43 | 44 | /*** 45 | * Use this setter for enabling logs. 46 | */ 47 | public void setEnableLog() { 48 | this.enableLog = true; 49 | } 50 | 51 | /*** 52 | * Use this setter for disabling logs. 53 | */ 54 | public void setDisableLog() { 55 | this.enableLog = false; 56 | } 57 | 58 | /*** 59 | * Log content - or not depending on enableLog property. 60 | * @param content: Value to be logged. 61 | */ 62 | public void logIt(String content) { 63 | logIt(content, true); 64 | } 65 | 66 | /*** 67 | * Log content - or not depending on enableLog property. 68 | * @param addLineBreakAtEnd Add a new line at the end of string, this will make easier to read logs. 69 | * @param content: Value to be logged. 70 | */ 71 | public void logIt(String content, boolean addLineBreakAtEnd) { 72 | if (enableLog) { 73 | this.testLog.log(Level.INFO, addLineBreakAtEnd ? content + "\n" : content); 74 | } 75 | } 76 | 77 | /*** 78 | * Simple helper to log all entries from a given list, line per line. 79 | * @param list: A list of strings. 80 | */ 81 | public void logAllEntries(List list) { 82 | logAllEntries(list, true); 83 | } 84 | 85 | /*** 86 | * Simple helper to log all entries from a given list, line per line. 87 | * @param addLineBreakAtEnd Add a new line at the end of string, this will make easier to read logs. 88 | * @param list: A list of strings. 89 | */ 90 | public void logAllEntries(List list, boolean addLineBreakAtEnd) { 91 | logAllEntries(list, false, addLineBreakAtEnd); 92 | } 93 | 94 | /*** 95 | * Simple helper to log all entries from a given list, line per line. 96 | * @param addLineBreakAtEnd Add a new line at the end of string, this will make easier to read logs. 97 | * @param oneLogPerEntry Each entry will be logged individually. 98 | * @param list: A list of strings. 99 | */ 100 | public void logAllEntries(List list, boolean oneLogPerEntry, boolean addLineBreakAtEnd) { 101 | if (oneLogPerEntry) { 102 | for (String entry : list) { 103 | logIt(addLineBreakAtEnd ? entry + "\n" : entry); 104 | } 105 | } else { 106 | String finalLog = ""; 107 | for (String entry : list) { 108 | finalLog += addLineBreakAtEnd ? entry + "\n" : entry; 109 | } 110 | logIt(finalLog); 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/misc/CalendarHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.misc; 2 | 3 | import java.text.DateFormat; 4 | import java.text.Format; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | import java.util.GregorianCalendar; 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class CalendarHelper { 17 | 18 | private final static String DEFAULT_DATE_PATTERN = "MM/dd/yyyy' 'HH:mm:ss"; 19 | 20 | /*** 21 | * Helper to extract a human readable date from a timestamp using a given date/time format. 22 | * @param timestamp: The long timestamp to be converted in human readable date. 23 | * @return A human readable date time. 24 | */ 25 | public static String convertTimestampToDate(long timestamp) { 26 | return convertTimestampToDate(timestamp, DEFAULT_DATE_PATTERN); 27 | } 28 | 29 | /*** 30 | * Helper to extract a human readable date from a timestamp using a given date/time format. 31 | * @param timestamp: The long timestamp to be converted in human readable date. 32 | * @param dateTimeFormat: Date Time format to be used. 33 | * @return A human readable date time. 34 | */ 35 | public static String convertTimestampToDate(long timestamp, String dateTimeFormat) { 36 | Date date = new Date(timestamp); 37 | Format format = new SimpleDateFormat(dateTimeFormat); 38 | return format.format(date); 39 | } 40 | 41 | /*** 42 | * Helper to create dates with high accuracy in order to be used specially along with Activity Scope. 43 | * @param date: A date... 44 | * @param hour: A hour... 45 | * @param minutes: Minutes... 46 | * @throws Exception 47 | */ 48 | public static Long convertDateToTimestamp(Date date, Integer hour, Integer minutes, Integer seconds) throws Exception { 49 | Calendar cal = Calendar.getInstance(); 50 | cal.setTime(date); 51 | int year = cal.get(Calendar.YEAR); 52 | int month = cal.get(Calendar.MONTH); 53 | int day = cal.get(Calendar.DAY_OF_MONTH); 54 | return new GregorianCalendar(year, month, day, hour, minutes, seconds).getTime().getTime(); 55 | } 56 | 57 | public static String getCurrentTimeAndDate() { 58 | Date date = new Date(); 59 | DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss"); 60 | return dateFormat.format(date); 61 | } 62 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/misc/RandomValuesHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.misc; 2 | 3 | import org.apache.commons.lang.RandomStringUtils; 4 | 5 | import java.util.Random; 6 | import java.util.concurrent.ThreadLocalRandom; 7 | 8 | /************************************************************ 9 | * © Copyright 2019 HP Development Company, L.P. 10 | * SPDX-License-Identifier: MIT 11 | * 12 | * Smart Test Framework 13 | ************************************************************/ 14 | public class RandomValuesHelper { 15 | 16 | /** 17 | * Helper to generate a random value given a threshold. 18 | * 19 | * @param minValue: Min value of threshold. 20 | * @param maxValue: Max value of threshold. 21 | * @return 22 | */ 23 | public static Double generateRandomDouble(double minValue, double maxValue) { 24 | Random random = new Random(); 25 | return (minValue + random.nextDouble() * (maxValue - minValue)); 26 | } 27 | 28 | /** 29 | * Helper to generate a random value given a threshold. 30 | * 31 | * @param minValue: Min value of threshold. 32 | * @param maxValue: Max value of threshold. 33 | * @return 34 | */ 35 | public static Integer generateRandomInt(int minValue, int maxValue) { 36 | return ThreadLocalRandom.current().nextInt(minValue, maxValue + 1); 37 | } 38 | 39 | /** 40 | * Simple helper that generates a random value. 41 | * 42 | * @param length 43 | * @return 44 | */ 45 | public static String generateAlphabetic(int length) { 46 | return generateAlphabetic(length, false); 47 | } 48 | 49 | /** 50 | * Simple helper that generates a random value. 51 | * 52 | * @param length 53 | * @param upperCase 54 | * @return 55 | */ 56 | public static String generateAlphabetic(int length, boolean upperCase) { 57 | return upperCase ? RandomStringUtils.randomAlphabetic(length).toUpperCase() : RandomStringUtils.randomAlphabetic(length).toLowerCase(); 58 | } 59 | 60 | /** 61 | * Simple helper that generates a random value. 62 | * 63 | * @param length 64 | * @return 65 | */ 66 | public static String generateRandomAlphanumeric(int length) { 67 | return RandomStringUtils.randomAlphanumeric(length); 68 | } 69 | 70 | /** 71 | * Simple helper that generates a random value. 72 | * 73 | * @param length 74 | * @return 75 | */ 76 | public static String generateRandomNumeric(int length) { 77 | return RandomStringUtils.randomNumeric(length); 78 | } 79 | 80 | //region To Be Deprecate 81 | 82 | 83 | //endregion 84 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/misc/StringsHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.misc; 2 | 3 | import java.util.List; 4 | 5 | /************************************************************ 6 | * © Copyright 2019 HP Development Company, L.P. 7 | * SPDX-License-Identifier: MIT 8 | * 9 | * Smart Test Framework 10 | ************************************************************/ 11 | public class StringsHelper { 12 | 13 | /*** 14 | * Helper that return all list content in a row separate by a given csv separator. 15 | * @param content: The list. 16 | * @return 17 | */ 18 | public static String returnAllListContentInRow(List content) { 19 | return returnAllListContentInRow(content, ""); 20 | } 21 | 22 | /*** 23 | * Helper that return all list content in a row separate by a given csv separator. 24 | * @param content: The list. 25 | * @param separator: A separator that will be added among each list entry when assembling everything in a single row. 26 | * @return 27 | */ 28 | public static String returnAllListContentInRow(List content, String separator) { 29 | String finalString = ""; 30 | for (int i = 0; i < content.size(); i++) { 31 | finalString += (i + 1) < content.size() ? content.get(i) + separator : content.get(i); 32 | } 33 | return finalString; 34 | } 35 | 36 | /** 37 | * Simple helper to mask string, in order to prevent it getting exposed in logs, such as passwords or any other sensitive info. 38 | * 39 | * @param content 40 | * @return 41 | */ 42 | public static String maskString(String content) { 43 | return maskString(content, ""); 44 | } 45 | 46 | /** 47 | * Simple helper to mask string, in order to prevent it getting exposed in logs, such as passwords or any other sensitive info. 48 | * 49 | * @param content: The content to be replaced 50 | * @param replaceBy 51 | * @return 52 | */ 53 | public static String maskString(String content, String replaceBy) { 54 | String defaultReplace = "*"; 55 | int passLength = content.length(); 56 | String maskedString = ""; 57 | for (Integer i = 0; i < passLength; i++) { 58 | maskedString += replaceBy.isEmpty() ? defaultReplace : replaceBy; 59 | } 60 | return maskedString; 61 | } 62 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/misc/VisualWarningsHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.misc; 2 | 3 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 4 | 5 | import javax.swing.*; 6 | import java.util.List; 7 | 8 | /************************************************************ 9 | * © Copyright 2019 HP Development Company, L.P. 10 | * SPDX-License-Identifier: MIT 11 | * 12 | * Smart Test Framework 13 | ************************************************************/ 14 | public class VisualWarningsHelper { 15 | 16 | /*** 17 | * Show a pop up with the given info. 18 | * Used in semi-automated tests. 19 | * @param title: A title for the dialog. 20 | * @param message: A message for dialog's content. 21 | */ 22 | public static void showDialogInfo(String title, String message) throws InterruptedException { 23 | showDialog(title, message, JOptionPane.INFORMATION_MESSAGE); 24 | } 25 | 26 | /*** 27 | * Show a pop up with the given info. 28 | * Used in semi-automated tests. 29 | * @param title: A title for the dialog. 30 | * @param message: A message for dialog's content. 31 | */ 32 | public static void showDialogInfo(String title, String message, int waitSecAfterDismiss) throws InterruptedException { 33 | showDialog(title, message, JOptionPane.INFORMATION_MESSAGE, waitSecAfterDismiss); 34 | } 35 | 36 | /*** 37 | * Show a pop up with the given info. 38 | * Used in semi-automated tests. 39 | * @param title: A title for the dialog. 40 | * @param message: A message for dialog's content. 41 | * @param jOptionPane: The type of the dialog. 42 | */ 43 | public static void showDialog(String title, String message, int jOptionPane) throws InterruptedException { 44 | showDialog(title, message, jOptionPane, 0); 45 | } 46 | 47 | /*** 48 | * Show a pop up with the given info. 49 | * Used in semi-automated tests. 50 | * @param title: A title for the dialog. 51 | * @param message: A message for dialog's content. 52 | * @param jOptionPane: The type of the dialog. 53 | */ 54 | public static void showDialog(String title, String message, int jOptionPane, int waitSecAfterDismiss) throws InterruptedException { 55 | JOptionPane.showMessageDialog(null, message, title, jOptionPane); 56 | if (waitSecAfterDismiss > 0) 57 | new WaitHelper().waitSeconds(waitSecAfterDismiss); 58 | } 59 | 60 | 61 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/network/NetworkHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.network; 2 | 3 | import com.github.jeansantos38.stf.framework.logger.TestLog; 4 | import com.github.jeansantos38.stf.framework.regex.RegexHelper; 5 | import org.testng.annotations.Test; 6 | 7 | import java.net.InetAddress; 8 | import java.net.NetworkInterface; 9 | import java.net.SocketException; 10 | import java.util.Enumeration; 11 | 12 | /************************************************************ 13 | * © Copyright 2019 HP Development Company, L.P. 14 | * SPDX-License-Identifier: MIT 15 | * 16 | * Smart Test Framework 17 | ************************************************************/ 18 | public class NetworkHelper { 19 | 20 | 21 | public static String retrieveLocalIPv4Address(String networkInterface) throws SocketException { 22 | return retrieveLocalIpAddress(IpVersion.IPV4, networkInterface); 23 | } 24 | 25 | public static String retrieveLocalIPv6Address(String networkInterface) throws SocketException { 26 | return retrieveLocalIpAddress(IpVersion.IPV6, networkInterface); 27 | } 28 | 29 | /*** 30 | * Helper to retrieve the ip address from a given network interface. 31 | * Works in a best effort basis, should return the first non-loopback IP address it can find. 32 | * @param networkInterface: Network interface name. 33 | * @return Its IP address. 34 | * @throws SocketException 35 | */ 36 | private static String retrieveLocalIpAddress(IpVersion ipVersion, String networkInterface) throws SocketException { 37 | NetworkInterface ni = NetworkInterface.getByName(networkInterface); 38 | if (ni == null) { 39 | new TestLog().logIt(String.format("It seems the selected network interface %s does not exist." + 40 | "\nTry any other from this list:\n %s", networkInterface, listAllNetworkInterfacesAvailable())); 41 | return ""; 42 | } 43 | Enumeration inetAddresses = ni.getInetAddresses(); 44 | String myIP = ""; 45 | while (inetAddresses.hasMoreElements()) { 46 | InetAddress ia = inetAddresses.nextElement(); 47 | if (!ia.isLinkLocalAddress()) { 48 | switch (ipVersion) { 49 | case IPV4: 50 | if (isValidIpv4(ia.getHostAddress())) { 51 | return ia.getHostAddress(); 52 | } 53 | break; 54 | case IPV6: 55 | if (isValidIpv6(ia.getHostAddress())) { 56 | return ia.getHostAddress(); 57 | } 58 | break; 59 | } 60 | } 61 | } 62 | return myIP; 63 | } 64 | 65 | /** 66 | * Helper that lists all available network interfaces. 67 | * 68 | * @return 69 | * @throws SocketException 70 | */ 71 | public static String listAllNetworkInterfacesAvailable() throws SocketException { 72 | Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); 73 | String finalString = ""; 74 | 75 | while (interfaces.hasMoreElements()) { 76 | NetworkInterface networkInterface = interfaces.nextElement(); 77 | finalString += networkInterface.getName() + " # "; 78 | } 79 | return finalString; 80 | } 81 | 82 | public static boolean isValidIpv6(String ipAddress) { 83 | return RegexHelper.isMatch("(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))", 84 | ipAddress); 85 | } 86 | 87 | public static boolean isValidIpv4(String ipAddress) { 88 | return RegexHelper.isMatch("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", 89 | ipAddress); 90 | } 91 | 92 | public enum IpVersion {IPV4, IPV6} 93 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/regex/RegexHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.regex; 2 | 3 | import com.github.jeansantos38.stf.framework.logger.TestLog; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class RegexHelper { 17 | 18 | private TestLog testLog; 19 | public static final String REGEX_GUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; 20 | public static final String HTTP_ERROR_CODES_REGEX = "([4||5][0-9][0-9])"; 21 | public static final String STRING_FORMAT_PATTERN_TBR_REGEX = "[%][0-9]*[$][a-z]"; 22 | public static final String REGEX_FACEBOOK_AUTHENTICATION_CODE = "([^=])\\w+(?=&)"; 23 | public static final String REGEX_FIRST_UUID_OCTET = "[0-9a-f]{8}(?=-)"; 24 | public static final String CONTENT_OR_REGEX_PATTERN_NULL_OR_EMPTY = "The content to be searched or the REGEX pattern cannot be null\\empty!"; 25 | 26 | /** 27 | * Default Constructor 28 | */ 29 | public RegexHelper(TestLog testLog) { 30 | this.testLog = testLog; 31 | } 32 | 33 | /** 34 | * Simple helper that check if a string does match with a given regex pattern. 35 | * 36 | * @param regexPattern 37 | * @param value 38 | * @return 39 | */ 40 | public static boolean isMatch(String regexPattern, String value) { 41 | Pattern pattern = Pattern.compile(regexPattern); 42 | Matcher matcher = pattern.matcher(value); 43 | return matcher.find(); 44 | } 45 | 46 | /*** 47 | * Helper to find a match using a given pattern. 48 | * @param fullContent: The content where the helper will be searching for a match. 49 | * @param pattern: The regex pattern. 50 | * @return 51 | */ 52 | public static Matcher returnMatch(String fullContent, String pattern) throws Exception { 53 | evaluatePatternAndFullContent(fullContent, pattern); 54 | Pattern finalPattern = Pattern.compile(pattern); 55 | Matcher matcher = finalPattern.matcher(fullContent); 56 | return matcher; 57 | } 58 | 59 | /*** 60 | * Helper to find a string using a given pattern. 61 | * @param fullContent: The content where the helper will be searching for a match. 62 | * @param pattern: The regex pattern. 63 | * @return 64 | */ 65 | public static String returnFirstMatchFrom(String fullContent, String pattern) throws Exception { 66 | evaluatePatternAndFullContent(fullContent, pattern); 67 | List matches = returnAllMatchesFrom(fullContent, pattern); 68 | if (matches.size() == 0) { 69 | return ""; 70 | } 71 | return matches.get(0); 72 | } 73 | 74 | /*** 75 | * Helper to find all matching string using a give pattern. 76 | * @param fullContent: The content where the helper will be searching for a match. 77 | * @param pattern: The regex pattern. 78 | * @return 79 | */ 80 | public static List returnAllMatchesFrom(String fullContent, String pattern) throws Exception { 81 | Matcher matcher = returnMatch(fullContent, pattern); 82 | List allReferences = new ArrayList<>(); 83 | // Find all matches 84 | while (matcher.find()) { 85 | // Get the matching string 86 | allReferences.add(matcher.group()); 87 | } 88 | return allReferences; 89 | } 90 | 91 | 92 | /** 93 | * Helper to find and replace the first match found. 94 | * 95 | * @param fullContent: The content where the helper will be searching for a match. 96 | * @param pattern: The regex pattern. 97 | * @param replacement: The new value. 98 | * @return 99 | * @throws Exception 100 | */ 101 | public static String findReplaceFirstMatch(String fullContent, String pattern, String replacement) throws Exception { 102 | return returnMatch(fullContent, pattern).replaceFirst(replacement); 103 | } 104 | 105 | /** 106 | * Helper to find and replace all matches found. 107 | * 108 | * @param fullContent: The content where the helper will be searching for a match. 109 | * @param pattern: The regex pattern. 110 | * @param replacement: The new value. 111 | * @return 112 | * @throws Exception 113 | */ 114 | public static String findReplaceAllMatches(String fullContent, String pattern, String replacement) throws Exception { 115 | return returnMatch(fullContent, pattern).replaceAll(replacement); 116 | } 117 | 118 | /** 119 | * Helper that returns the match for a given group. 120 | * 121 | * @param fullContent: The content where the helper will be searching for a match. 122 | * @param pattern: The regex pattern. 123 | * @param groupIndex: Remember that group index starts from 1. 124 | * @return 125 | * @throws Exception 126 | */ 127 | public static String returnMatchFromGroup(String fullContent, String pattern, int groupIndex) throws Exception { 128 | Matcher matcher = returnMatch(fullContent, pattern); 129 | String targetMatch = ""; 130 | // Find all matches 131 | while (matcher.find()) { 132 | // Get the matching string 133 | targetMatch = (matcher.group(groupIndex)); 134 | break; 135 | } 136 | return targetMatch; 137 | } 138 | 139 | /*** 140 | * Evaluate if pattern and content meets the minimum requirements. 141 | * @param fullContent: The content where the helper will be searching for a match. 142 | * @param pattern: The regex pattern. 143 | * @throws Exception 144 | */ 145 | private static void evaluatePatternAndFullContent(String fullContent, String pattern) throws Exception { 146 | if (fullContent == null || fullContent.isEmpty() || pattern == null || pattern.isEmpty()) { 147 | throw new Exception(CONTENT_OR_REGEX_PATTERN_NULL_OR_EMPTY); 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/serialization/DeserializeHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.serialization; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; 5 | import com.fasterxml.jackson.dataformat.xml.XmlMapper; 6 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 7 | import com.github.jeansantos38.stf.enums.serialization.SerializationType; 8 | 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class DeserializeHelper { 17 | 18 | /*** 19 | * Deserialize a content into a given class. This one use default module for XML. 20 | * @param tClass: The class type. 21 | * @param serializationType: Supported serialization types. 22 | * @param payload: The content to be deserialized. 23 | * @param : The returned class. 24 | * @return The deserialized content. 25 | * @throws Exception 26 | */ 27 | public static T deserializeStringToObject(Class tClass, SerializationType serializationType, String payload) throws Exception { 28 | return deserializeStringToObject(tClass, serializationType, null, payload); 29 | } 30 | 31 | /*** 32 | * Deserialize a content into a given class. This one use configurable module for XML. 33 | * @param tClass: The class type. 34 | * @param serializationType: Supported serialization types. 35 | * @param module: Custom XML wrapper/parser module. 36 | * @param payload: The content to be deserialized. 37 | * @param : The returned class. 38 | * @return The deserialized content. 39 | * @throws Exception 40 | */ 41 | public static T deserializeStringToObject(Class tClass, SerializationType serializationType, JacksonXmlModule module, String payload) throws Exception { 42 | T obj; 43 | switch (serializationType) { 44 | case JSON: 45 | obj = new ObjectMapper().readValue(payload, tClass); 46 | return obj; 47 | case XML: 48 | if (module != null) { 49 | obj = new XmlMapper(module).readValue(payload, tClass); 50 | } else { 51 | obj = new XmlMapper().readValue(payload, tClass); 52 | } 53 | return obj; 54 | case YAML: 55 | ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); 56 | return objectMapper.readValue(payload, tClass); 57 | default: 58 | throw new Exception(String.format("The %1$s serialization type is not supported.", serializationType.toString())); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/serialization/JsonParserHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.serialization; 2 | 3 | import com.jayway.jsonpath.Configuration; 4 | import com.jayway.jsonpath.JsonPath; 5 | import com.jayway.jsonpath.Option; 6 | import net.minidev.json.JSONArray; 7 | 8 | /************************************************************ 9 | * © Copyright 2019 HP Development Company, L.P. 10 | * SPDX-License-Identifier: MIT 11 | * 12 | * Smart Test Framework 13 | ************************************************************/ 14 | public class JsonParserHelper { 15 | 16 | /** 17 | * Use regular cast to get the values. 18 | * @param jsonPathExpression 19 | * @param jsonDocument 20 | * @param options 21 | * @return can be (String), (List) or (JSONArray) - it will depends on what you're trying to get. 22 | */ 23 | public static Object readJsonPath(String jsonPathExpression, String jsonDocument, Option... options) { 24 | return JsonPath.using(setConfig(options)).parse(jsonDocument).read(jsonPathExpression); 25 | } 26 | 27 | /** 28 | * Return any match as object so it's possible to interact with it and all its attributes. 29 | * It works in a best effort basis, even some errors in path expressions might be suppressed. 30 | * @param jsonPathExpression 31 | * @param jsonDocument 32 | * @return 33 | */ 34 | 35 | public static JSONArray tryReadJsonPath(String jsonPathExpression, String jsonDocument) { 36 | return JsonPath.using(setConfig(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS)).parse(jsonDocument).read(jsonPathExpression); 37 | } 38 | 39 | /** 40 | * It will return an attribute value or convert an entire json object to plain text. 41 | * It works grate for getting an attribute value. For a path that returns an object it might return a lot of information 42 | * accordingly the size of json object. 43 | * @param jsonPathExpression 44 | * @param jsonToBeParsed 45 | * @return 46 | */ 47 | public static String tryParseJsonPathToString(String jsonPathExpression, String jsonToBeParsed) { 48 | JSONArray match = JsonPath.using(setConfig(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS)).parse(jsonToBeParsed).read(jsonPathExpression); 49 | return match.get(0).toString(); 50 | } 51 | 52 | private static Configuration setConfig(Option... options) { 53 | Configuration configuration = Configuration.defaultConfiguration(); 54 | return configuration.addOptions(options); 55 | } 56 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/serialization/SerializeHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.serialization; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; 8 | import com.fasterxml.jackson.dataformat.xml.XmlMapper; 9 | import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; 10 | import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; 11 | import com.fasterxml.jackson.dataformat.yaml.YAMLParser; 12 | 13 | /************************************************************ 14 | * © Copyright 2019 HP Development Company, L.P. 15 | * SPDX-License-Identifier: MIT 16 | * 17 | * Smart Test Framework 18 | ************************************************************/ 19 | public class SerializeHelper { 20 | 21 | /*** 22 | * Serialize a Json Object into String. 23 | * @param jsonObject: The json object 24 | * @param jsonSerializationInclusion: To define which properties of Java Beans are to be included in serialization. 25 | * @return The serialized object as string. 26 | * @throws JsonProcessingException 27 | */ 28 | public static String serializeJsonObject(Object jsonObject, JsonInclude.Include jsonSerializationInclusion) throws JsonProcessingException { 29 | ObjectMapper mapper = new ObjectMapper(); 30 | if (jsonSerializationInclusion != null) { 31 | mapper.setSerializationInclusion(jsonSerializationInclusion); 32 | } 33 | return mapper.writeValueAsString(jsonObject); 34 | } 35 | 36 | /*** 37 | * Serialize a XML object into String. 38 | * @param xmlObject: The xml object. 39 | * @return The serialized object as string. 40 | * @throws JsonProcessingException 41 | */ 42 | public static String serializeXmlObject(Object xmlObject) throws JsonProcessingException { 43 | return serializeXmlObject(xmlObject, null); 44 | } 45 | 46 | /*** 47 | * Serialize a XML object into String. 48 | * @param xmlObject: The xml object. 49 | * @param jacksonXmlModule: The wrapper configuration for this deserialization. 50 | * @return The serialized object as string. 51 | * @throws JsonProcessingException 52 | */ 53 | public static String serializeXmlObject(Object xmlObject, JacksonXmlModule jacksonXmlModule) throws JsonProcessingException { 54 | XmlMapper xmlMapper; 55 | if (jacksonXmlModule != null) { 56 | xmlMapper = new XmlMapper(jacksonXmlModule); 57 | } else { 58 | xmlMapper = new XmlMapper(); 59 | } 60 | return xmlMapper.writeValueAsString(xmlObject); 61 | } 62 | 63 | /*** 64 | * Serialize a Yaml object into String. 65 | * @param yamlObject: The yaml object. 66 | * @return The serialized object as string. 67 | * @throws JsonProcessingException 68 | */ 69 | public static String serializeYamlObject(Object yamlObject) throws JsonProcessingException { 70 | return serializeYamlObject(yamlObject, null, null); 71 | } 72 | 73 | /*** 74 | * Serialize a Yaml object into String. 75 | * @param yamlObject: The yaml object. 76 | * @return The serialized object as string. 77 | * @throws JsonProcessingException 78 | */ 79 | public static String serializeYamlObject(Object yamlObject, SerializationFeature serializationFeature, YAMLGenerator.Feature feature) throws JsonProcessingException { 80 | ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); 81 | 82 | if (serializationFeature != null) { 83 | mapper.disable(serializationFeature); 84 | } 85 | 86 | if (feature != null) { 87 | mapper = new ObjectMapper(new YAMLFactory().disable(feature)); 88 | } 89 | return mapper.writeValueAsString(yamlObject); 90 | } 91 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/main/java/com/github/jeansantos38/stf/framework/wait/WaitHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.wait; 2 | 3 | import com.github.jeansantos38.stf.enums.wait.ThreadWait; 4 | import com.github.jeansantos38.stf.framework.misc.RandomValuesHelper; 5 | 6 | /************************************************************ 7 | * © Copyright 2019 HP Development Company, L.P. 8 | * SPDX-License-Identifier: MIT 9 | * 10 | * Smart Test Framework 11 | ************************************************************/ 12 | public class WaitHelper { 13 | 14 | /** 15 | * Default constructor. 16 | */ 17 | public WaitHelper() { 18 | } 19 | 20 | /** 21 | * Helper that will wait during a random period of time of a give threshold. 22 | * 23 | * @param minWaitSec Min value to wait. 24 | * @param maxWaitSec Max value to wait. 25 | * @throws InterruptedException 26 | */ 27 | public void randomWait(double minWaitSec, double maxWaitSec) throws InterruptedException { 28 | Double random = RandomValuesHelper.generateRandomDouble(minWaitSec, maxWaitSec); 29 | random = random * 1000; 30 | long timeToWait = random.longValue(); 31 | Thread.sleep(timeToWait); 32 | } 33 | 34 | /** 35 | * Simple helper that will perform a thread sleep. 36 | * 37 | * @param waitSec: How many seconds. 38 | * @throws InterruptedException 39 | */ 40 | public void waitSeconds(double waitSec) throws InterruptedException { 41 | Double finalWait = waitSec; 42 | finalWait = finalWait * 1000; 43 | long timeToWait = finalWait.longValue(); 44 | Thread.sleep(timeToWait); 45 | } 46 | 47 | /** 48 | * Simple helper that will perform a thread sleep. 49 | * 50 | * @param waitMs: How many milliseconds. 51 | * @throws InterruptedException 52 | */ 53 | public void waitMilliseconds(double waitMs) throws InterruptedException { 54 | Double finalWait = waitMs; 55 | long timeToWait = finalWait.longValue(); 56 | Thread.sleep(timeToWait); 57 | } 58 | 59 | /** 60 | * Simple helper that performs thread sleep using a fix range of values. 61 | * 62 | * @param wait: How long should wait. 63 | * @throws Exception 64 | */ 65 | public void wait(ThreadWait wait) throws Exception { 66 | switch (wait) { 67 | case WAIT_1_SEC: 68 | Thread.sleep(1000); 69 | break; 70 | case WAIT_2_SEC: 71 | Thread.sleep(2000); 72 | break; 73 | case WAIT_3_SEC: 74 | Thread.sleep(3000); 75 | break; 76 | case WAIT_5_SEC: 77 | Thread.sleep(5000); 78 | break; 79 | case WAIT_10_SEC: 80 | Thread.sleep(10000); 81 | break; 82 | case WAIT_15_SEC: 83 | Thread.sleep(15000); 84 | break; 85 | case WAIT_30_SEC: 86 | Thread.sleep(30000); 87 | break; 88 | case WAIT_45_SEC: 89 | Thread.sleep(45000); 90 | break; 91 | case WAIT_60_SEC: 92 | Thread.sleep(60000); 93 | break; 94 | case WAIT_2_MIN: 95 | Thread.sleep(120000); 96 | break; 97 | case WAIT_3_MIN: 98 | Thread.sleep(180000); 99 | break; 100 | case WAIT_5_MIN: 101 | Thread.sleep(300000); 102 | break; 103 | case WAIT_10_MIN: 104 | Thread.sleep(600000); 105 | break; 106 | default: 107 | throw new Exception(String.format("%1$s is not supported yet!", wait.toString())); 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/base/MainTestBase.java: -------------------------------------------------------------------------------- 1 | package system.base; 2 | 3 | 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 6 | import org.testng.annotations.BeforeClass; 7 | import org.testng.annotations.Optional; 8 | import org.testng.annotations.Parameters; 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class MainTestBase { 17 | 18 | protected static TestLog testLog; 19 | protected WaitHelper waitHelper; 20 | 21 | @BeforeClass 22 | @Parameters({"optionalGlobalParameterExample"}) 23 | public void mainTestBaseInitialize(@Optional("") String param1) throws Exception { 24 | testLog = new TestLog(true); 25 | testLog.logIt("Parameter value provided from testRunConfig:" + param1); 26 | waitHelper = new WaitHelper(); 27 | } 28 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/Bicycle.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class Bicycle { 4 | 5 | public String color; 6 | 7 | public String price; 8 | 9 | public Bicycle() { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/Book.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class Book { 4 | 5 | public String author; 6 | 7 | public String price; 8 | 9 | public String category; 10 | 11 | public String title; 12 | 13 | public String isbn; 14 | 15 | public Book() { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/BooksStore.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class BooksStore { 4 | 5 | private Store store; 6 | 7 | private String expensive; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/Note.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class Note { 4 | public String to; 5 | public String from; 6 | public String heading; 7 | public String body; 8 | 9 | public Note() { 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/NoteDemoClass.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class NoteDemoClass { 4 | 5 | public Note note; 6 | 7 | public NoteDemoClass() { 8 | } 9 | 10 | public NoteDemoClass factory() { 11 | this.note = new Note(); 12 | note.body = "Don't forget that STF means Smart Test Framework"; 13 | note.from = "STF"; 14 | note.heading = "Urgent!"; 15 | note.to = "QA User"; 16 | return this; 17 | } 18 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/pojo/Store.java: -------------------------------------------------------------------------------- 1 | package system.pojo; 2 | 3 | public class Store { 4 | 5 | private Bicycle bicycle; 6 | 7 | private Book[] book; 8 | } 9 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/test/CalendarTests.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.regex.RegexHelper; 4 | import io.qameta.allure.*; 5 | import system.base.MainTestBase; 6 | import org.testng.Assert; 7 | import org.testng.annotations.Test; 8 | 9 | import static com.github.jeansantos38.stf.framework.misc.CalendarHelper.convertTimestampToDate; 10 | 11 | public class CalendarTests extends MainTestBase { 12 | 13 | @Test 14 | @Severity(SeverityLevel.MINOR) 15 | @Story("A QA should be capable of easily handling date formats using STF") 16 | @Description("Converting a timestamp in human readable date format") 17 | public void convertTimestampToDateTest() { 18 | String extractedDate = convertTimestampToDate(Long.parseLong("1613569411419")); 19 | String pattern = "([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2})"; 20 | Assert.assertTrue(RegexHelper.isMatch(pattern, extractedDate), String.format( 21 | "Expecting a date in this format: [MM/dd/yyyy HH:mm:ss], but got %s", extractedDate)); 22 | 23 | } 24 | 25 | @Test 26 | @Severity(SeverityLevel.MINOR) 27 | @Story("A QA should be capable of easily handling date formats using STF") 28 | @Description("Converting a timestamp in specific time format") 29 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 30 | public void convertTimestampUsingPattern() { 31 | String extractedDate = convertTimestampToDate(Long.parseLong("1613569411419"), "yyyy/dd/MM' 'HH:mm:ss"); 32 | String pattern = "([0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})"; 33 | Assert.assertTrue(RegexHelper.isMatch(pattern, extractedDate), String.format( 34 | "Expecting a date in this format: [yyyy/dd/MM HH:mm:ss], but got %s", extractedDate)); 35 | } 36 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/test/InputOutputTests.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 4 | import com.github.jeansantos38.stf.framework.misc.RandomValuesHelper; 5 | import io.qameta.allure.*; 6 | import system.base.MainTestBase; 7 | import org.testng.Assert; 8 | import org.testng.annotations.AfterClass; 9 | import org.testng.annotations.BeforeClass; 10 | import org.testng.annotations.Test; 11 | 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | 16 | public class InputOutputTests extends MainTestBase { 17 | 18 | String fullFilename; 19 | String content; 20 | 21 | @BeforeClass 22 | public void beforeClass() { 23 | testLog.logIt("Running before class steps"); 24 | fullFilename = System.getProperty("user.home") + String.format("/%s.txt", RandomValuesHelper.generateRandomAlphanumeric(6)); 25 | content = "This is the content to be written inside a file"; 26 | } 27 | 28 | @AfterClass 29 | public void afterClass() throws Exception { 30 | testLog.logIt("Running After class steps"); 31 | File file = new File(fullFilename); 32 | if (!file.delete()) { 33 | throw new Exception("Check cleanup the file was not deleted!"); 34 | } 35 | } 36 | 37 | @Test 38 | @Severity(SeverityLevel.MINOR) 39 | @Story("A QA should be to create a file in hard disk") 40 | @Description("Create a text file using any string as content") 41 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 42 | public void createFileOnDisk() throws IOException { 43 | //Create a text file inside a pre-defined folder with this content below 44 | try { 45 | InputOutputHelper.writeFile(content, fullFilename); 46 | } catch (Exception e) { 47 | testLog.logIt(e.getMessage()); 48 | Assert.fail("The file was not created!"); 49 | } 50 | } 51 | 52 | @Test(dependsOnMethods = "createFileOnDisk") 53 | @Severity(SeverityLevel.MINOR) 54 | @Story("A QA should be capable of easily reading files from hard disk") 55 | @Description("Read the file content created by previous test and check if its content matches") 56 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 57 | public void readCreatedFile() throws IOException { 58 | String contentFound = InputOutputHelper.readContentFromFile(fullFilename); 59 | Assert.assertTrue(contentFound.contains(content)); 60 | } 61 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/test/NetworkInterfaceTests.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.network.NetworkHelper; 4 | import org.testng.Assert; 5 | import org.testng.annotations.Optional; 6 | import org.testng.annotations.Parameters; 7 | import org.testng.annotations.Test; 8 | import system.base.MainTestBase; 9 | 10 | 11 | public class NetworkInterfaceTests extends MainTestBase { 12 | 13 | @Test 14 | @Parameters({"networkInterface"}) 15 | public void NetworkTests(@Optional("eth1") String networkInterface) throws Exception { 16 | String ipV4example = "192.168.0.100"; 17 | String ipV6example = "2804:14d:4c88:88c9:50a9:1074:3cb0:d7e6"; 18 | 19 | Assert.assertTrue(NetworkHelper.isValidIpv4(ipV4example)); 20 | Assert.assertTrue(NetworkHelper.isValidIpv6(ipV6example)); 21 | Assert.assertFalse(NetworkHelper.listAllNetworkInterfacesAvailable().isEmpty()); 22 | 23 | testLog.logIt(NetworkHelper.listAllNetworkInterfacesAvailable()); 24 | testLog.logIt(NetworkHelper.retrieveLocalIPv4Address(networkInterface)); 25 | testLog.logIt(NetworkHelper.retrieveLocalIPv6Address(networkInterface)); 26 | } 27 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/java/system/test/RegexTests.java: -------------------------------------------------------------------------------- 1 | package system.test; 2 | 3 | import com.github.jeansantos38.stf.framework.regex.RegexHelper; 4 | import io.qameta.allure.*; 5 | import org.testng.Assert; 6 | import org.testng.annotations.Test; 7 | 8 | import java.io.IOException; 9 | 10 | public class RegexTests { 11 | 12 | @Test(priority = 3) 13 | @Severity(SeverityLevel.NORMAL) 14 | @Story("A QA should be capable of easily using REGEX on STF") 15 | @Description("Check if pattern does exist in given text") 16 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 17 | public void regexFullMatch() throws IOException { 18 | String guid = "9be48fe8-20a5-4263-b097-d096b2e6309a"; 19 | Assert.assertTrue(RegexHelper.isMatch(RegexHelper.REGEX_GUID, guid)); 20 | } 21 | 22 | 23 | @Test(priority = 1) 24 | @Severity(SeverityLevel.NORMAL) 25 | @Story("A QA should be capable of easily using REGEX on STF") 26 | @Description("Check if a pattern can be found by Group Matching strategy") 27 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 28 | public void regexGroupMatch() throws Exception { 29 | String multipleValues = "cars123home"; 30 | Assert.assertEquals(RegexHelper.returnMatchFromGroup(multipleValues, "((cars))([0-9]{3})([a-z]{4})", 1), "cars"); 31 | Assert.assertEquals(RegexHelper.returnMatchFromGroup(multipleValues, "((cars))([0-9]{3})([a-z]{4})", 3), "123"); 32 | Assert.assertEquals(RegexHelper.returnMatchFromGroup(multipleValues, "((cars))([0-9]{3})([a-z]{4})", 4), "home"); 33 | String modifiedValue = RegexHelper.findReplaceFirstMatch(multipleValues, "[0-9]{3}", "000"); 34 | Assert.assertEquals(modifiedValue, "cars000home"); 35 | } 36 | 37 | @Test(priority = 2) 38 | @Severity(SeverityLevel.NORMAL) 39 | @Story("A QA should be capable of easily using REGEX on STF") 40 | @Description("Find and replace a given string by another using REGEX") 41 | @Link(name = "This could be a Link to your project Issue Tracker", url = "https://github.com/HPInc/smart-test-framework") 42 | public void regexFindReplace() throws Exception { 43 | String multipleValues = "cars123home"; 44 | String modifiedValue = RegexHelper.findReplaceFirstMatch(multipleValues, "[0-9]{3}", "000"); 45 | Assert.assertEquals(modifiedValue, "cars000home"); 46 | } 47 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/resources/booksStore.json: -------------------------------------------------------------------------------- 1 | { 2 | "store": { 3 | "book": [ 4 | { 5 | "category": "reference", 6 | "author": "Nigel Rees", 7 | "title": "Sayings of the Century", 8 | "price": 8.95 9 | }, 10 | { 11 | "category": "fiction", 12 | "author": "Evelyn Waugh", 13 | "title": "Sword of Honour", 14 | "price": 12.99 15 | }, 16 | { 17 | "category": "fiction", 18 | "author": "Herman Melville", 19 | "title": "Moby Dick", 20 | "isbn": "0-553-21311-3", 21 | "price": 8.99 22 | }, 23 | { 24 | "category": "fiction", 25 | "author": "J. R. R. Tolkien", 26 | "title": "The Lord of the Rings", 27 | "isbn": "0-395-19395-8", 28 | "price": 22.99 29 | } 30 | ], 31 | "bicycle": { 32 | "color": "red", 33 | "price": 19.95 34 | } 35 | }, 36 | "expensive": 10 37 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/resources/content.json: -------------------------------------------------------------------------------- 1 | { 2 | "note": { 3 | "to": "QA User", 4 | "from": "STF", 5 | "heading": "Urgent!", 6 | "body": "Don't forget that STF means Smart Test Framework" 7 | } 8 | } -------------------------------------------------------------------------------- /stf-misc-lib/src/test/resources/content.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Don't forget that STF means Smart Test Framework 5 | STF 6 | Urgent! 7 | QA User 8 | 9 | -------------------------------------------------------------------------------- /stf-misc-lib/src/test/resources/content.yml: -------------------------------------------------------------------------------- 1 | --- 2 | note: 3 | to: QA User 4 | from: STF 5 | heading: Urgent! 6 | body: Don't forget that STF means Smart Test Framework 7 | -------------------------------------------------------------------------------- /stf-misc-lib/testRunConfig/testRunConfig_misc-tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /stf-webdriver-lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | com.github.jeansantos38.stf 8 | smart-test-framework 9 | 1.3-SNAPSHOT 10 | 11 | 4.0.0 12 | 13 | stf-web-driver 14 | 1.3-SNAPSHOT 15 | jar 16 | 17 | STF-Webdriver 18 | https://github.com/HPInc/smart-test-framework 19 | 20 | 21 | 22 | 23 | com.github.jeansantos38.stf 24 | stf-misc 25 | 1.3.1-SNAPSHOT 26 | 27 | 28 | com.github.jeansantos38.stf 29 | stf-http-client 30 | 1.3-SNAPSHOT 31 | 32 | 33 | 34 | 35 | org.seleniumhq.selenium 36 | selenium-java 37 | 3.141.59 38 | 39 | 40 | 41 | org.seleniumhq.selenium 42 | selenium-firefox-driver 43 | 3.141.59 44 | 45 | 46 | 47 | org.seleniumhq.selenium 48 | selenium-chrome-driver 49 | 3.141.59 50 | 51 | 52 | 53 | org.seleniumhq.selenium 54 | selenium-ie-driver 55 | 3.141.59 56 | 57 | 58 | 59 | org.seleniumhq.selenium 60 | selenium-safari-driver 61 | 3.141.59 62 | 63 | 64 | 65 | org.seleniumhq.selenium 66 | selenium-edge-driver 67 | 3.141.59 68 | 69 | 70 | 71 | org.seleniumhq.selenium 72 | selenium-opera-driver 73 | 3.141.59 74 | 75 | 76 | 77 | io.appium 78 | java-client 79 | 7.1.0 80 | 81 | 82 | 83 | com.github.tomakehurst 84 | wiremock-standalone 85 | 2.23.2 86 | test 87 | 88 | 89 | 90 | 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-surefire-plugin 95 | ${maven.surefire.plugin.version} 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/enums/webdriver/SelectorType.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.webdriver; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum SelectorType { 10 | BY_ID, BY_XPATH, BY_CLASS_NAME, BY_CSS, BY_NAME, BY_TAG_NAME, BY_LINK, BY_PARTIAL_LINK 11 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/enums/webdriver/WebDriverAction.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.enums.webdriver; 2 | 3 | /************************************************************ 4 | * © Copyright 2019 HP Development Company, L.P. 5 | * SPDX-License-Identifier: MIT 6 | * 7 | * Smart Test Framework 8 | ************************************************************/ 9 | public enum WebDriverAction { 10 | CLICK, EVALUATE_CLICK, DOUBLE_CLICK, EVALUATE_DOUBLE_CLICK, DRAG_AND_DROP, DRAG_AND_DROP_BY, CONTEXT_CLICK, EVALUATE_CONTEXT_CLICK, SEND_KEYS, EVALUATE_SEND_KEYS, MOVE_TO_ELEMENT 11 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/framework/datadriven/WebDriverDataDrivenCommon.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.datadriven; 2 | 3 | import com.github.jeansantos38.stf.enums.webdriver.SelectorType; 4 | import com.github.jeansantos38.stf.framework.regex.RegexHelper; 5 | 6 | /************************************************************ 7 | * © Copyright 2019 HP Development Company, L.P. 8 | * SPDX-License-Identifier: MIT 9 | * 10 | * Smart Test Framework 11 | ************************************************************/ 12 | public abstract class WebDriverDataDrivenCommon { 13 | 14 | /*** 15 | * This helper prevents wrong combinations of operators and the content to be validated. 16 | * @param operator: The operator will defined what type of assert will be used. 17 | * @param contentType: The content type will define how the values will be asserted. 18 | * @throws Exception 19 | */ 20 | protected void verifyIfOperatorSupportsContent(String operator, String contentType) throws Exception { 21 | boolean notSupported = false; 22 | 23 | switch (operator) { 24 | case "EqualTo": 25 | case "NotEqualTo": 26 | break; 27 | 28 | case "Contains": 29 | if (contentType.equals("boolean") || !contentType.equals("string")) { 30 | notSupported = true; 31 | } 32 | break; 33 | 34 | case "NotContain": 35 | if (contentType.equals("boolean") || !contentType.equals("string")) { 36 | notSupported = true; 37 | } 38 | break; 39 | 40 | case "GreaterThan": 41 | if (contentType.equals("boolean") || contentType.equals("string")) { 42 | notSupported = true; 43 | } 44 | break; 45 | 46 | case "GreaterThanOrEqualTo": 47 | if (contentType.equals("boolean") || contentType.equals("string")) { 48 | notSupported = true; 49 | } 50 | break; 51 | 52 | case "LesserThan": 53 | if (contentType.equals("boolean") || contentType.equals("string")) { 54 | notSupported = true; 55 | } 56 | break; 57 | 58 | case "LesserThanOrEqualTo": 59 | if (contentType.equals("boolean") || contentType.equals("string")) { 60 | notSupported = true; 61 | } 62 | break; 63 | 64 | case "Exists": 65 | if (contentType.equals("boolean") || contentType.contains("picture_")) { 66 | notSupported = true; 67 | } 68 | break; 69 | 70 | case "NotExist": 71 | if (contentType.equals("boolean") || contentType.contains("picture_")) { 72 | notSupported = true; 73 | } 74 | break; 75 | 76 | default: 77 | throw new Exception(String.format("The action type:[%1$s] is not supported!!!", operator)); 78 | 79 | } 80 | if (notSupported) { 81 | throw new Exception(String.format("The operator:[%1$s] cannot be applied to the action:[%2$s].", contentType, operator)); 82 | } 83 | } 84 | 85 | /*** 86 | * Simple helper that returns the Selector type based on data driven WebDriver action. 87 | * @param locator 88 | * @return 89 | * @throws Exception 90 | */ 91 | protected SelectorType returnSelectorType(String locator) throws Exception { 92 | String filteredAction = RegexHelper.returnFirstMatchFrom(locator, "(by[A-Z])\\w+"); 93 | switch (filteredAction) { 94 | case "byId": 95 | return SelectorType.BY_ID; 96 | case "byXpath": 97 | return SelectorType.BY_XPATH; 98 | case "byClass": 99 | return SelectorType.BY_CLASS_NAME; 100 | case "byCss": 101 | return SelectorType.BY_CSS; 102 | case "byName": 103 | return SelectorType.BY_NAME; 104 | case "byTagName": 105 | return SelectorType.BY_TAG_NAME; 106 | case "byLink": 107 | return SelectorType.BY_LINK; 108 | case "byPartialLink": 109 | return SelectorType.BY_PARTIAL_LINK; 110 | default: 111 | throw new Exception(String.format("The action type:[%1$s] is not supported!!!")); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/framework/datadriven/WebDriverDataDrivenHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.datadriven; 2 | 3 | import com.github.jeansantos38.stf.framework.webdriver.WebDriverAppiumHelper; 4 | import com.github.jeansantos38.stf.framework.webdriver.WebDriverSeleniumHelper; 5 | import com.github.jeansantos38.stf.dataclasses.datadriven.DataDriven; 6 | import com.github.jeansantos38.stf.dataclasses.datadriven.SmartDataDriven; 7 | import com.github.jeansantos38.stf.dataclasses.datadriven.Statement; 8 | import com.github.jeansantos38.stf.enums.serialization.SerializationType; 9 | import com.github.jeansantos38.stf.framework.io.InputOutputHelper; 10 | import com.github.jeansantos38.stf.framework.logger.TestLog; 11 | import com.github.jeansantos38.stf.framework.serialization.DeserializeHelper; 12 | 13 | 14 | import java.util.Arrays; 15 | 16 | /************************************************************ 17 | * © Copyright 2019 HP Development Company, L.P. 18 | * SPDX-License-Identifier: MIT 19 | * 20 | * Smart Test Framework 21 | ************************************************************/ 22 | public class WebDriverDataDrivenHelper { 23 | 24 | private TestLog testLog; 25 | 26 | /*** 27 | * Default constructor. 28 | * @param testLog: LoggerQA class instance. 29 | */ 30 | public WebDriverDataDrivenHelper(TestLog testLog) { 31 | this.testLog = testLog; 32 | } 33 | 34 | /*** 35 | * Helper that executes Appium data driven instruction sets. 36 | * @param webDriverAppiumHelper 37 | * @param dataDrivenFileFullPath 38 | * @param instructionSet 39 | * @throws Exception 40 | */ 41 | public void executeDataDriven(WebDriverAppiumHelper webDriverAppiumHelper, String dataDrivenFileFullPath, String instructionSet) throws Exception { 42 | executeDataDriven(webDriverAppiumHelper, dataDrivenFileFullPath, instructionSet); 43 | } 44 | 45 | /*** 46 | * Helper that executes Selenium data driven instruction sets. 47 | * @param webDriverSeleniumHelper 48 | * @param dataDrivenFileFullPath 49 | * @param instructionSet 50 | * @throws Exception 51 | */ 52 | public void executeDataDriven(WebDriverSeleniumHelper webDriverSeleniumHelper, String dataDrivenFileFullPath, String instructionSet) throws Exception { 53 | executeDataDriven(null, webDriverSeleniumHelper, dataDrivenFileFullPath, instructionSet); 54 | } 55 | 56 | /*** 57 | * Main execute data driven helper. 58 | * @param webDriverAppiumHelper 59 | * @param webDriverSeleniumHelper 60 | * @param dataDrivenFileFullPath 61 | * @param instructionSet 62 | * @throws Exception 63 | */ 64 | private void executeDataDriven(WebDriverAppiumHelper webDriverAppiumHelper, WebDriverSeleniumHelper webDriverSeleniumHelper, String dataDrivenFileFullPath, String instructionSet) throws Exception { 65 | String dataDrivenContent = InputOutputHelper.readContentFromFile(dataDrivenFileFullPath); 66 | DataDriven dataDriven = DeserializeHelper.deserializeStringToObject(DataDriven.class, SerializationType.JSON, dataDrivenContent); 67 | SmartDataDriven smartDataDriven = Arrays.stream(dataDriven.SmartDataDriven).filter(x -> x.instructionSet.equals(instructionSet)).findAny().orElse(null); 68 | 69 | if (smartDataDriven == null) { 70 | throw new Exception(String.format("The provided instruction set [%1$s] does not exist in the given data driven file [%2$s]. Please review it and try again!!!", instructionSet, dataDrivenFileFullPath)); 71 | } 72 | 73 | for (int i = 0; i < smartDataDriven.statements.length; i++) { 74 | SetWebDriverInstructionSet setWebDriverInstructionSet = null; 75 | AssertWebDriverInstructionSet assertWebDriverInstructionSet = null; 76 | 77 | boolean isAssert = smartDataDriven.statements[i].statement.purpose.equals("assert"); 78 | Statement statement = smartDataDriven.statements[i].statement; 79 | 80 | testLog.logIt(String.format("Executing data driven for agent [%1$s] with [%2$s] operation!", smartDataDriven.statements[i].statement.agent, isAssert ? "ASSERT" : "SET")); 81 | switch (smartDataDriven.statements[i].statement.agent) { 82 | case "appium": 83 | if (isAssert) { 84 | if (assertWebDriverInstructionSet == null) 85 | assertWebDriverInstructionSet = new AssertWebDriverInstructionSet(this.testLog, webDriverAppiumHelper); 86 | assertWebDriverInstructionSet.dataDrivenAssert(statement); 87 | } else { 88 | if (setWebDriverInstructionSet == null) 89 | setWebDriverInstructionSet = new SetWebDriverInstructionSet(this.testLog, webDriverAppiumHelper); 90 | setWebDriverInstructionSet.dataDrivenSet(statement); 91 | } 92 | break; 93 | 94 | case "selenium": 95 | if (isAssert) { 96 | if (assertWebDriverInstructionSet == null) 97 | assertWebDriverInstructionSet = new AssertWebDriverInstructionSet(this.testLog, webDriverSeleniumHelper); 98 | assertWebDriverInstructionSet.dataDrivenAssert(statement); 99 | } else { 100 | if (setWebDriverInstructionSet == null) 101 | setWebDriverInstructionSet = new SetWebDriverInstructionSet(this.testLog, webDriverSeleniumHelper); 102 | setWebDriverInstructionSet.dataDrivenSet(statement); 103 | } 104 | break; 105 | 106 | default: 107 | throw new Exception(String.format("The agent [%1$s] is not supported yet!", smartDataDriven.statements[i].statement.agent)); 108 | } 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/framework/webdriver/WebDriverAppiumHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.webdriver; 2 | 3 | import com.github.jeansantos38.stf.enums.webdriver.SelectorType; 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | import io.appium.java_client.MobileElement; 6 | import io.appium.java_client.ios.IOSElement; 7 | import org.openqa.selenium.Platform; 8 | import org.openqa.selenium.WebElement; 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class WebDriverAppiumHelper extends WebDriverCommonHelper { 17 | 18 | /*** 19 | * Default constructor. 20 | */ 21 | public WebDriverAppiumHelper() { 22 | } 23 | 24 | public WebDriverAppiumHelper(Platform platform, int webDriverTimeout, TestLog testLog) { 25 | setLogger(testLog); 26 | setAppiumTheMainUsage(true); 27 | setWebDriverWaitTimeoutSeconds(webDriverTimeout); 28 | setDevicePlatform(platform); 29 | 30 | 31 | warnStfUsage(); 32 | } 33 | // region Common Area 34 | 35 | /*** 36 | * Helper to send values to an web element. 37 | * @param platform What platform? 38 | * @param selectorType: What is the type of this selector? What selector? 39 | * @param selectorId: The element selector. 40 | * @param value: The value to be be sent. 41 | * @throws Exception 42 | */ 43 | public void sendKeys(Platform platform, SelectorType selectorType, String selectorId, String value) throws Exception { 44 | WebElement element = first(selectorType, selectorId); 45 | switch (platform) { 46 | case ANDROID: 47 | element.sendKeys(value); 48 | break; 49 | case IOS: 50 | IOSElement tempElement = (IOSElement) element; 51 | tempElement.setValue(value); 52 | break; 53 | default: 54 | throw new Exception(String.format("The webdriver platform %1$s is not supported yet.", platform.toString())); 55 | } 56 | } 57 | 58 | /** 59 | * This helper performs a click in a element. 60 | * The difference between this helper and a _common First.Click() is that this one is intended to Mobile elements instead regular WebElements - otherwise I can guarantee that you'll face instabilities while testing Apps. 61 | * 62 | * @param selectorType: What is the type of this selector? What selector? 63 | * @param selectorId: The element selector. 64 | * @throws Exception 65 | */ 66 | public void tap(SelectorType selectorType, String selectorId) throws Exception { 67 | MobileElement element; 68 | element = (MobileElement) first(selectorType, selectorId); 69 | element.click(); 70 | } 71 | 72 | //endregion 73 | 74 | // region iOS Area 75 | 76 | /*** 77 | * Helper to send values to an web element for iOS. 78 | * @param selectorType: What is the type of this selector? What selector? 79 | * @param selectorId: The element selector. 80 | * @param value: The value to be be sent. 81 | * @throws Exception 82 | */ 83 | public void sendKeysToiOS(SelectorType selectorType, String selectorId, String value) throws Exception { 84 | sendKeys(Platform.IOS, selectorType, selectorId, value); 85 | } 86 | // endregion 87 | 88 | // region Android Area 89 | 90 | /*** 91 | * Helper to send values to an web element for Android. 92 | * @param selectorType: What is the type of this selector? What selector? 93 | * @param selectorId: The element selector. 94 | * @param value: The value to be be sent. 95 | * @throws Exception 96 | */ 97 | public void sendKeysToAndroid(SelectorType selectorType, String selectorId, String value) throws Exception { 98 | sendKeys(Platform.ANDROID, selectorType, selectorId, value); 99 | } 100 | // endregion 101 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/main/java/com/github/jeansantos38/stf/framework/webdriver/WebDriverSeleniumHelper.java: -------------------------------------------------------------------------------- 1 | package com.github.jeansantos38.stf.framework.webdriver; 2 | 3 | import com.github.jeansantos38.stf.framework.logger.TestLog; 4 | import com.github.jeansantos38.stf.framework.wait.WaitHelper; 5 | import org.openqa.selenium.Keys; 6 | import org.openqa.selenium.WebElement; 7 | import org.openqa.selenium.interactions.Actions; 8 | 9 | 10 | /************************************************************ 11 | * © Copyright 2019 HP Development Company, L.P. 12 | * SPDX-License-Identifier: MIT 13 | * 14 | * Smart Test Framework 15 | ************************************************************/ 16 | public class WebDriverSeleniumHelper extends WebDriverCommonHelper { 17 | 18 | /*** 19 | * Default constructor. 20 | */ 21 | public WebDriverSeleniumHelper() { 22 | } 23 | 24 | public WebDriverSeleniumHelper(int webDriverTimeoutSeconds, TestLog testLog) { 25 | setLogger(testLog); 26 | setAppiumTheMainUsage(false); 27 | setWebDriverWaitTimeoutSeconds(webDriverTimeoutSeconds); 28 | warnStfUsage(); 29 | } 30 | 31 | 32 | /*** 33 | * Helper to scroll the page in order to reach an specific element. 34 | * @param webElement: Webelement. 35 | * @throws InterruptedException 36 | */ 37 | public void scrollToWebElement(WebElement webElement) throws InterruptedException { 38 | executeJavascript(webElement, "arguments[0].scrollIntoView(true);", false, 1); 39 | } 40 | 41 | /*** 42 | * Switch from default web context into a given webFrame. 43 | * @param webFrameId: The id of web frame. 44 | */ 45 | public void switchToWebFrame(String webFrameId) { 46 | this.getSeleniumDriver().switchTo().frame(webFrameId); 47 | } 48 | 49 | /*** 50 | * Switch from current web frame back to Default web context. 51 | */ 52 | public void switchToDefaultWebContext() { 53 | this.getSeleniumDriver().switchTo().defaultContent(); 54 | } 55 | 56 | /** 57 | * Helper that perform a key press by using Selenium Action Send keys. 58 | * 59 | * @param key: Key to be pressed. 60 | * @throws InterruptedException 61 | */ 62 | public void pressKey(Keys key) throws InterruptedException { 63 | pressKeys(new Keys[]{key}); 64 | } 65 | 66 | /** 67 | * Helper that perform key presses by using Selenium Action Send keys. 68 | * 69 | * @param keys: Keys to be pressed. 70 | * @throws InterruptedException 71 | */ 72 | public void pressKeys(Keys[] keys) throws InterruptedException { 73 | Actions actions = new Actions(this.getSeleniumDriver()); 74 | for (Keys key : keys) { 75 | actions.sendKeys(key).perform(); 76 | new WaitHelper().waitMilliseconds(this.DEFAULT_FOR_DELAY_BETWEEN_ACTIONS_MS); 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/test/java/system/test/base/MainTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | 4 | import com.github.jeansantos38.stf.framework.logger.TestLog; 5 | import org.testng.annotations.*; 6 | 7 | public class MainTestBase { 8 | 9 | protected static TestLog testLog; 10 | 11 | @BeforeClass 12 | @Parameters({"optionalGlobalParameterExample"}) 13 | public void mainTestBaseInitialize(@Optional("") String param1) { 14 | testLog = new TestLog(true); 15 | 16 | testLog.logIt("Parameter value provided from testRunConfig:" + param1); 17 | } 18 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/test/java/system/test/base/WebUiTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | import org.openqa.selenium.PageLoadStrategy; 4 | import org.openqa.selenium.WebDriver; 5 | import org.openqa.selenium.chrome.ChromeOptions; 6 | import org.openqa.selenium.remote.DesiredCapabilities; 7 | import org.openqa.selenium.remote.RemoteWebDriver; 8 | import org.testng.annotations.BeforeClass; 9 | import org.testng.annotations.Parameters; 10 | 11 | import java.net.MalformedURLException; 12 | import java.net.URL; 13 | 14 | public class WebUiTestBase extends WireMockTestBase { 15 | 16 | protected String seleniumGridServerUrl; 17 | private ChromeOptions chromeOptions; 18 | protected DesiredCapabilities desiredCapabilities; 19 | 20 | @Parameters({ 21 | "param_SeleniumGridHost", 22 | "param_SeleniumGridPort", 23 | "param_BaseGridUrl", 24 | "param_IsSelenoid", 25 | "param_BrowserName", 26 | "param_BrowserVersion" 27 | }) 28 | @BeforeClass 29 | public void initializeWebUiClass( 30 | String param_SeleniumGridHost, 31 | String param_SeleniumGridPort, 32 | String param_BaseGridUrl, 33 | Boolean param_IsSelenoid, 34 | String param_BrowserName, 35 | String param_BrowserVersion) { 36 | 37 | chromeOptions = configureChromeOptions(); 38 | desiredCapabilities = configureDesiredCapabilities( 39 | chromeOptions, 40 | param_BrowserName, 41 | param_BrowserVersion, 42 | param_IsSelenoid); 43 | 44 | seleniumGridServerUrl = String.format(param_BaseGridUrl, param_SeleniumGridHost, param_SeleniumGridPort); 45 | } 46 | 47 | private ChromeOptions configureChromeOptions() { 48 | ChromeOptions chromeOptions = new ChromeOptions(); 49 | chromeOptions.addArguments("--allow-running-insecure-content"); 50 | chromeOptions.addArguments("--disable-web-security"); 51 | chromeOptions.addArguments("window-size=1920,1080"); 52 | chromeOptions.addArguments("enable-automation"); 53 | chromeOptions.addArguments("--no-sandbox"); 54 | chromeOptions.addArguments("--disable-extensions"); 55 | chromeOptions.addArguments("--dns-prefetch-disable"); 56 | chromeOptions.addArguments("--disable-gpu"); 57 | chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL); 58 | return chromeOptions; 59 | } 60 | 61 | private DesiredCapabilities configureDesiredCapabilities( 62 | ChromeOptions chromeOptions, 63 | String browserName, 64 | String browserVersionString, 65 | boolean isSelenoid) { 66 | DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); 67 | desiredCapabilities.setBrowserName(browserName); 68 | desiredCapabilities.setVersion(browserVersionString); 69 | if (isSelenoid) { 70 | desiredCapabilities.setCapability("enableVNC", true); 71 | } 72 | desiredCapabilities.setCapability("name", "STF Web Ui demo tests"); 73 | desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); 74 | return desiredCapabilities; 75 | } 76 | 77 | protected WebDriver startChromeBrowser( 78 | DesiredCapabilities desiredCapabilities, 79 | String seleniumGridServerUrl) throws MalformedURLException { 80 | return new RemoteWebDriver(new URL(seleniumGridServerUrl), desiredCapabilities); 81 | } 82 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/test/java/system/test/base/WireMockTestBase.java: -------------------------------------------------------------------------------- 1 | package system.test.base; 2 | 3 | import com.github.tomakehurst.wiremock.WireMockServer; 4 | import org.testng.annotations.AfterClass; 5 | import org.testng.annotations.BeforeClass; 6 | import org.testng.annotations.Parameters; 7 | 8 | import java.net.SocketException; 9 | 10 | import static com.github.tomakehurst.wiremock.client.WireMock.*; 11 | import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; 12 | 13 | public class WireMockTestBase extends MainTestBase { 14 | 15 | protected WireMockServer wireMockServer; 16 | protected String uiTestsBaseUrl; 17 | 18 | @Parameters({ 19 | "param_WiremockExternalIP", 20 | "param_WiremockPort", 21 | "param_WiremockUiEndpoint" 22 | }) 23 | @BeforeClass 24 | public void initializeMockServer( 25 | String param_WiremockExternalIP, 26 | Integer param_WiremockPort, 27 | String param_WiremockUiEndpoint) throws SocketException { 28 | wireMockServer = new WireMockServer(options().port(param_WiremockPort)); 29 | wireMockServer.start(); 30 | 31 | uiTestsBaseUrl = String.format("http://%s:%s%s", param_WiremockExternalIP, param_WiremockPort, param_WiremockUiEndpoint); 32 | 33 | mockHtmlPage(wireMockServer, param_WiremockUiEndpoint + "/form"); 34 | mockHtmlPageWithTable(wireMockServer, param_WiremockUiEndpoint + "/table"); 35 | } 36 | 37 | @AfterClass 38 | public void endMockServer() { 39 | if (wireMockServer != null && wireMockServer.isRunning()) { 40 | wireMockServer.stop(); 41 | } 42 | } 43 | 44 | private void mockHtmlPage(WireMockServer wireMockServer, String endpoint) { 45 | wireMockServer.stubFor( 46 | get(urlEqualTo(endpoint)) 47 | .willReturn(aResponse().withBodyFile("stf_demo_form.html"))); 48 | } 49 | 50 | private void mockHtmlPageWithTable(WireMockServer wireMockServer, String endpoint) { 51 | wireMockServer.stubFor( 52 | get(urlEqualTo(endpoint)) 53 | .willReturn(aResponse().withBodyFile("table.html"))); 54 | } 55 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/src/test/resources/__files/stf_demo_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | STF DEMO FORM 9 | 10 | 11 | Can you handle all elements below? 12 | 13 | 14 | This is a 15 | partial Link Test 16 | 17 | 18 | This is a Link 19 | Test 20 | 21 | 22 | Textbox1: 23 | 24 | 25 | Textbox2: 26 | 27 | 28 | 29 | Radio button 31 | rbtn value 1 rbtn value 2 33 | 34 | 35 | Check boxes Option 1 Option 38 | 2 39 | 40 | 41 | Select file 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | Drop Down 51 | 52 | Super option 1 53 | Super option 2 54 | Super option 3 55 | Super option 4 56 | Super option 5 57 | 58 | 59 | 60 | 61 | 62 | 63 | Click Here 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /stf-webdriver-lib/src/test/resources/webUiDatadriven/dataDriven_webcontent.json: -------------------------------------------------------------------------------- 1 | { 2 | "SmartDataDriven": [ 3 | { 4 | "instructionSet": "set_validValues1", 5 | "statements": [ 6 | { 7 | "statement": { 8 | "agent": "selenium", 9 | "purpose": "set", 10 | "selector": "input[name='tbx1']", 11 | "locator": "byCss", 12 | "action": "setField", 13 | "contentType": "string", 14 | "content": [ 15 | "1 hello this is a test from STF" 16 | ] 17 | } 18 | }, 19 | { 20 | "statement": { 21 | "agent": "selenium", 22 | "purpose": "set", 23 | "selector": "input[name='tbx2']", 24 | "locator": "byCss", 25 | "action": "setField", 26 | "contentType": "string", 27 | "content": [ 28 | "some input from stf" 29 | ] 30 | } 31 | }, 32 | { 33 | "statement": { 34 | "agent": "selenium", 35 | "purpose": "set", 36 | "selector": "radio-1", 37 | "locator": "byId", 38 | "action": "setField", 39 | "contentType": "boolean", 40 | "content": [ 41 | true 42 | ] 43 | } 44 | }, 45 | { 46 | "statement": { 47 | "agent": "selenium", 48 | "purpose": "set", 49 | "selector": "#option-0", 50 | "locator": "byCss", 51 | "action": "setField", 52 | "contentType": "boolean", 53 | "content": [ 54 | true 55 | ] 56 | } 57 | }, 58 | { 59 | "statement": { 60 | "agent": "selenium", 61 | "purpose": "set", 62 | "selector": "#dropdown", 63 | "locator": "byCss", 64 | "action": "setField", 65 | "contentType": "string", 66 | "content": [ 67 | "Super option 4" 68 | ] 69 | } 70 | } 71 | ] 72 | }, 73 | { 74 | "instructionSet": "assert_validValues1", 75 | "statements": [ 76 | { 77 | "statement": { 78 | "agent": "selenium", 79 | "purpose": "assert", 80 | "selector": "input[name='tbx1']", 81 | "locator": "byCss", 82 | "operator": "EqualTo", 83 | "action": "assertField", 84 | "contentType": "string", 85 | "content": [ 86 | "1 hello this is a test from STF" 87 | ] 88 | } 89 | }, 90 | { 91 | "statement": { 92 | "agent": "selenium", 93 | "purpose": "assert", 94 | "selector": "input[name='tbx2']", 95 | "locator": "byCss", 96 | "operator": "EqualTo", 97 | "action": "assertField", 98 | "contentType": "string", 99 | "content": [ 100 | "some input from stf" 101 | ] 102 | } 103 | }, 104 | { 105 | "statement": { 106 | "agent": "selenium", 107 | "purpose": "assert", 108 | "selector": "radio-1", 109 | "locator": "byId", 110 | "operator": "EqualTo", 111 | "action": "assertField", 112 | "contentType": "boolean", 113 | "content": [ 114 | true 115 | ] 116 | } 117 | }, 118 | { 119 | "statement": { 120 | "agent": "selenium", 121 | "purpose": "assert", 122 | "selector": "#option-0", 123 | "locator": "byCss", 124 | "operator": "EqualTo", 125 | "action": "assertField", 126 | "contentType": "boolean", 127 | "content": [ 128 | true 129 | ] 130 | } 131 | }, 132 | { 133 | "statement": { 134 | "agent": "selenium", 135 | "purpose": "assert", 136 | "selector": "#dropdown", 137 | "locator": "byCss", 138 | "operator": "EqualTo", 139 | "action": "assertField", 140 | "contentType": "string", 141 | "content": [ 142 | "Super option 4" 143 | ] 144 | } 145 | } 146 | ] 147 | } 148 | ] 149 | } -------------------------------------------------------------------------------- /stf-webdriver-lib/testRunConfig/testRunConfig_webcontent_ui_demo-tests.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | --------------------------------------------------------------------------------
Drop Down