Skip to content

Commit 957c68f

Browse files
committed
Fix: Ensure AI-generated test class names match file names and update generator logic for concise class names
1 parent 5c62436 commit 957c68f

File tree

9 files changed

+149
-94
lines changed

9 files changed

+149
-94
lines changed

RAG_Demo.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ Start with the comprehensive demonstration in `NLGenerationAndChatbotTest.java`
3434

3535
Explore this class to see how RAG and NLP can supercharge your test automation workflow!
3636

37+
38+
39+
40+
3741
# How to Run the RAG Embedding Cache Demo
3842

3943
1. **Build the project:**

embedding_cache_ollama.json

Lines changed: 15 additions & 0 deletions
Large diffs are not rendered by default.

rag_embedding_cache.json

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

src/main/java/org/k11techlab/framework/ai/nlp/NLTestGenerator.java

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -375,20 +375,22 @@ private TestType detectTestType(String description) {
375375
* Generate test name from description
376376
*/
377377
private String generateTestName(String description) {
378-
// Convert natural language to camelCase test name
379-
String[] words = description.toLowerCase()
380-
.replaceAll("[^a-zA-Z0-9\\s]", "")
381-
.split("\\s+");
382-
383-
StringBuilder testName = new StringBuilder("test");
384-
for (String word : words) {
385-
if (!word.isEmpty() && word.length() > 2) {
386-
testName.append(Character.toUpperCase(word.charAt(0)))
387-
.append(word.substring(1));
388-
}
378+
// Always use a concise, valid class name for generated tests
379+
// If the description contains 'login', use 'GeneratedLoginTest', etc.
380+
String desc = description.toLowerCase();
381+
if (desc.contains("login")) {
382+
return "GeneratedLoginTest";
383+
} else if (desc.contains("e-commerce") || desc.contains("shopping") || desc.contains("cart") || desc.contains("checkout")) {
384+
return "GeneratedEcommerceTest";
385+
} else if (desc.contains("search")) {
386+
return "GeneratedSearchTest";
387+
} else if (desc.contains("form")) {
388+
return "GeneratedFormTest";
389+
} else if (desc.contains("api")) {
390+
return "GeneratedApiTest";
389391
}
390-
391-
return testName.toString();
392+
// Fallback: use 'GeneratedTest'
393+
return "GeneratedTest";
392394
}
393395

394396
/**

src/test/ai_generated_tests/GeneratedLoginTest.java

Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -2,59 +2,55 @@
22

33
import org.openqa.selenium.WebDriver;
44
import org.openqa.selenium.WebElement;
5-
import org.openqa.selenium.support.ui.WebDriverWait;
65
import org.openqa.selenium.support.ui.ExpectedConditions;
7-
import org.testng.annotations.Test;
8-
import org.testng.annotations.BeforeMethod;
6+
import org.openqa.selenium.support.ui.WebDriverWait;
97
import org.testng.annotations.AfterMethod;
10-
import org.k11techlab.framework.BaseSeleniumTest;
8+
import org.testng.annotations.BeforeMethod;
9+
import org.testng.annotations.Test;
1110

12-
public class testYouAreExpertJavaSeleniumTestDeveloperGenerateTestngTestClassForLogIntoWebsiteUsingUsernameTestuserAndPasswordTestpassThenVerifyTheDashboardDisplayedUseTheWebdriverPatternGetdriverPageObjectModelAndNotUsePlaceholderCodeOutputOnlyValidCompilableJavaClass extends BaseSeleniumTest {
11+
public class GeneratedLoginTest extends BaseSeleniumTest {
12+
13+
private WebDriver driver;
1314

1415
@BeforeMethod
15-
public void setUp() {
16+
public void setup() {
17+
driver = getDriver();
1618
getDriver().get("https://demo.testsite.com");
1719
}
1820

1921
@Test
2022
public void testLoginAndVerifyDashboard() {
21-
try {
22-
WebElement usernameField = elementHealer.findElement("Username field");
23-
WebElement passwordField = elementHealer.findElement("Password field");
24-
WebElement loginButton = elementHealer.findElement("Login button");
25-
26-
usernameField.sendKeys("testuser");
27-
passwordField.sendKeys("testpass");
28-
loginButton.click();
29-
30-
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
31-
wait.until(ExpectedConditions.urlContains("dashboard"));
23+
WebElement usernameInput = elementHealer.findElement("username input field");
24+
WebElement passwordInput = elementHealer.findElement("password input field");
25+
WebElement loginButton = elementHealer.findElement("login button");
3226

33-
// Add validations for dashboard elements if needed
27+
usernameInput.sendKeys("testuser");
28+
passwordInput.sendKeys("testpass");
29+
loginButton.click();
3430

35-
// Add log messages for successful login and dashboard verification
36-
System.out.println("Login successful. Dashboard displayed.");
31+
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
32+
wait.until(ExpectedConditions.urlContains("dashboard"));
3733

38-
} catch (Exception e) {
39-
// Capture screenshot on failure
40-
captureScreenshot("loginAndVerifyDashboard");
34+
// Add meaningful assertions and log messages for verification
35+
// Example: Assert.assertTrue(driver.getCurrentUrl().contains("dashboard"), "Dashboard not displayed");
4136

42-
// Handle any exceptions
43-
System.out.println("Error occurred during login and dashboard verification: " + e.getMessage());
44-
}
4537
}
4638

4739
@AfterMethod
48-
public void tearDown() {
49-
driver.quit();
40+
public void teardown() {
41+
if (driver != null) {
42+
driver.quit();
43+
}
5044
}
5145
}
5246

53-
/*
47+
/*
5448
📚 **Knowledge Sources Used:**
55-
1. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 61.2)
56-
2. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 44.1)
57-
3. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 43.2)
49+
1. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 83.7)
50+
2. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 72.9)
51+
3. built-in-solutions (Category: ERROR_SOLUTIONS, Relevance: 62.1)
5852
53+
*/
54+
/*
5955
💡 **Tip:** This response was enhanced with context-aware knowledge retrieval for better accuracy.
60-
*/
56+
*/
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package ai_generated_tests;
2+
3+
import org.testng.Assert;
4+
import org.testng.annotations.Test;
5+
import java.io.FileInputStream;
6+
import java.util.Properties;
7+
8+
public class SampleConfigUsageTest {
9+
@Test
10+
public void testAIProviderOrderConfig() throws Exception {
11+
Properties props = new Properties();
12+
props.load(new FileInputStream("config/chatbot.ai.properties"));
13+
String providerOrder = props.getProperty("ai.provider.priority");
14+
Assert.assertNotNull(providerOrder);
15+
Assert.assertTrue(providerOrder.contains("OPENAI"));
16+
}
17+
}
18+

src/test/ai_generated_tests/conversation_history.txt

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,62 +8,80 @@ I'm here to help you with test automation using our advanced AI-enhanced framewo
88
⚙️ **Help with framework** setup and configuration
99
🌟 **Share best practices** for reliable test automation
1010

11+
/*
1112
💡 **Try saying:**
1213
- "Generate a login test for https://example.com"
1314
- "Help me debug this failing test"
1415
- "Review my test code for improvements"
1516
- "Show me best practices for element finding"
1617

17-
**Session ID:** `dd121dff-1cc3-4586-848f-4d5e4c43d3b4`
18+
*/
19+
**Session ID:** `62e2f225-2461-49e3-b934-0000a230a9e4`
1820
**Mode:** General test automation help and guidance
1921

2022
How can I help you today? 😊
2123
User: I'm working on testing an e-commerce website called 'TechStore' at https://techstore.example.com
22-
Bot: 💬 Based on the test examples provided, here is some actionable advice for testing the 'TechStore' e-commerce website:
24+
Bot: 💬 Based on the test examples provided, here are some actionable tips for testing the 'TechStore' e-commerce website:
2325

24-
1. **Form Submission Test**: You can create a test case to simulate form submission on the 'TechStore' website. This test can include filling out the contact form, submitting it, and verifying the success message. Make sure to handle any potential errors using appropriate error handling mechanisms.
26+
1. Consider creating test cases for form submissions: Utilize the AI-Enhanced Form Test with Error Handling example to test the submission of forms on the website. Make sure to handle any potential errors that may arise during the form submission process.
2527

26-
2. **Dropdown Selection Test**: Another test case can involve testing the dropdown selection functionality on the website, such as selecting a country from a dropdown menu. Use WebDriverWait to ensure the options load properly before making a selection and verify that the correct option is selected.
28+
2. Test dropdown selection functionality: Use the AI-Enhanced Dropdown Selection Test example to test the dropdown selection feature on the website. Verify that users can select options from dropdown menus accurately.
2729

28-
3. **Login Test Example**: Implement a test case for the login functionality on the 'TechStore' website. This can include entering a username and password, clicking the login button, and verifying the welcome message or successful login confirmation.
30+
3. Test the login functionality: Implement the AI-Enhanced Login Test Example to test the login process on the 'TechStore' website. Ensure that users can successfully log in with valid credentials and access the relevant features of the website.
2931

30-
4. **Element Locators**: Utilize elementHealer to efficiently locate elements on the website by their identifiers (e.g., name, id, class) to interact with them during test execution.
32+
4. Utilize elementHealer for locating web elements: Use the elementHealer.findElement method to locate specific elements on the website such as input fields, buttons, and messages. This will help in interacting with the elements during the test automation process.
3133

32-
5. **Error Handling**: Implement error handling mechanisms to capture and handle any ElementNotFoundException or other exceptions that may occur during test execution, ensuring that failures are properly managed and reported.
34+
5. Incorporate wait strategies: Implement wait strategies such as WebDriverWait to ensure that web elements are loaded properly before interacting with them. This will help in avoiding synchronization issues during test execution.
3335

34-
6. **Screenshot Capture**: Consider adding functionality to capture screenshots in case of test failures, providing visual evidence for debugging purposes.
35-
36-
By incorporating these test examples and best practices into your test automation strategy for the 'TechStore' website, you can ensure comprehensive test coverage and efficient test execution.
36+
By following these tips and utilizing the provided test examples, you can create effective and reliable test automation scripts for testing the 'TechStore' e-commerce website.
3737

38+
/*
3839
📚 **Knowledge Sources Used:**
3940
1. built-in-examples (Category: TEST_EXAMPLES, Relevance: 24.0)
4041
2. built-in-examples (Category: TEST_EXAMPLES, Relevance: 21.0)
4142
3. built-in-examples (Category: TEST_EXAMPLES, Relevance: 21.0)
4243

44+
*/
45+
/*
4346
💡 **Tip:** This response was enhanced with context-aware knowledge retrieval for better accuracy.
4447

48+
*/
4549
User: The login functionality is on the /login page. Users can login with email and password.
46-
Bot: 💬 To automate the login functionality on the /login page, you can follow the example from Knowledge Source 1.
50+
Bot: 💬 Based on the provided test examples, you can create a test case for the login functionality as follows:
51+
52+
@Test
53+
public void testLoginFunctionality() {
54+
WebElement emailField = elementHealer.findElement("email input field");
55+
WebElement passwordField = elementHealer.findElement("password input field");
56+
WebElement loginButton = elementHealer.findElement("login button");
57+
58+
emailField.sendKeys("testuser@example.com");
59+
passwordField.sendKeys("password123");
60+
loginButton.click();
61+
62+
WebElement welcomeMessage = elementHealer.findElement("welcome message");
63+
assert welcomeMessage.isDisplayed();
64+
}
4765

48-
1. Use Selenium to locate the username input field, password input field, and login submit button on the login page.
49-
2. Use the `sendKeys` method to input the email and password into the respective fields.
50-
3. Use the `click` method to submit the login form.
51-
4. Use Selenium to locate the welcome message element that appears after a successful login.
52-
5. Use an assertion to verify that the welcome message is displayed, indicating a successful login.
66+
In this test case, make sure to replace the element locator values ("email input field", "password input field", "login button", "welcome message") with the actual locators for the elements on the /login page.
5367

54-
Additionally, you can enhance your test automation script by incorporating error handling similar to the example in Knowledge Source 2. This will help you capture any unexpected issues during the login process and handle them gracefully in your automation script.
68+
Additionally, consider incorporating error handling in case any elements are not found or if the login fails. You can refer to the testFormSubmission() example for guidance on handling errors.
5569

56-
Remember to handle any potential timing issues by incorporating explicit waits, as demonstrated in the dropdown selection test example from Knowledge Source 3.
70+
Lastly, ensure to wait for the elements to be visible or present before interacting with them, similar to what was done in the testDropdownSelection() example.
5771

58-
By following these steps and best practices from the provided test examples, you can create a robust and reliable automated test for the login functionality on the /login page.
72+
By following these steps and customizing the test case to fit your specific application, you can effectively automate testing for the login functionality on the /login page.
5973

74+
/*
6075
📚 **Knowledge Sources Used:**
6176
1. built-in-examples (Category: TEST_EXAMPLES, Relevance: 44.3)
6277
2. built-in-examples (Category: TEST_EXAMPLES, Relevance: 31.5)
6378
3. built-in-examples (Category: TEST_EXAMPLES, Relevance: 22.5)
6479

80+
*/
81+
/*
6582
💡 **Tip:** This response was enhanced with context-aware knowledge retrieval for better accuracy.
6683

84+
*/
6785
User: Now generate a comprehensive login test that includes both positive and negative scenarios
6886
Bot: I'd be happy to generate a test for you! 🎯
6987

src/test/java/org/k11techlab/framework_unittests/aiTests/NLGenerationAndChatbotTest.java

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,40 @@ private void saveToFile(String fileName, String content) {
3535
.replaceAll("(?<![\\w.])driver\\.get\\(", "getDriver().get(")
3636
.replaceAll("(?<![\\w.])driver\\.findElement\\(", "getDriver().findElement(");
3737

38+
39+
// Comment out AI-generated metadata blocks (knowledge sources, tips, summaries, etc.)
40+
// This will wrap any block starting with 'ℹ️', '📚', '💡', '?', or 'In the above Java class:' and following lines until a blank line or end of string
41+
String[] lines = patchedContent.split("\r?\n");
42+
StringBuilder commentedContentBuilder = new StringBuilder();
43+
boolean inMetaBlock = false;
44+
for (int i = 0; i < lines.length; i++) {
45+
String line = lines[i];
46+
String trimmed = line.trim();
47+
if (!inMetaBlock && (trimmed.startsWith("ℹ️") || trimmed.startsWith("📚") || trimmed.startsWith("💡") || trimmed.startsWith("?") || trimmed.startsWith("In the above Java class:"))) {
48+
inMetaBlock = true;
49+
commentedContentBuilder.append("/*\n");
50+
}
51+
if (inMetaBlock) {
52+
commentedContentBuilder.append(line).append("\n");
53+
// End block on blank line or last line
54+
boolean isLastLine = (i == lines.length - 1);
55+
boolean isBlank = trimmed.isEmpty();
56+
if (isBlank || isLastLine) {
57+
commentedContentBuilder.append("*/\n");
58+
inMetaBlock = false;
59+
}
60+
} else {
61+
commentedContentBuilder.append(line).append("\n");
62+
}
63+
}
64+
String commentedContent = commentedContentBuilder.toString();
65+
3866
// Debug output: print the generated code
39-
System.out.println("--- DEBUG: Generated code for " + fileName + " ---\n" + patchedContent + "\n--- END ---");
67+
System.out.println("--- DEBUG: Generated code for " + fileName + " ---\n" + commentedContent + "\n--- END ---");
4068

4169
// Always save the file, even if it's a placeholder or not a valid class
4270
try (java.io.FileWriter writer = new java.io.FileWriter(fullPath)) {
43-
writer.write(patchedContent);
71+
writer.write(commentedContent);
4472
System.out.println("📁 Saved output to: " + fullPath);
4573
} catch (Exception e) {
4674
System.out.println("❌ Failed to save file: " + fullPath + " - " + e.getMessage());

testartifacts/assets/chatbot_nlp_flow

Lines changed: 0 additions & 27 deletions
This file was deleted.

0 commit comments

Comments
 (0)