Skip to content

feature: add solution on daily 10/26 KT #277

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

khanh5923
Copy link
Contributor

@khanh5923 khanh5923 commented Jan 10, 2025

Hi, mọi người xem giúp em bài này nhé. Vòng lặp for ở dòng 17 em thấy nó không được hay lắm, em có thử dùng evaluate() để bỏ thuộc tính "readonly" rồi điền giá trị vào mà không được :)))))

----------- GÓC HỎI NHỎ :)))))) -----------
hú anh @minhphong306 và mọi người, em định làm một project cá nhân nhỏ để bỏ vô CV cho hay, thì em tính viết một bộ testcase như manual test í rồi từ mấy testcase đó viết script cho automation. Thì hong biết em cần thêm gì cho hay hơn không anh nhỉ, mọi người với anh cho em thêm ý kiến nhé. Em cảm ơn ạ.

Summary by CodeRabbit

  • New Features
    • Added a test specification for product purchasing functionality
    • Implemented a test case for buying products from a wishlist
    • Added dialog event handling and validation for purchase process

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces a Playwright test specification for a product purchasing functionality. The code defines an interface Product and a buyProduct function that iterates through a list of products, attempting to purchase them by clicking buttons on a web page. If some products are not initially visible, the function uses pagination to locate and purchase them. The test case navigates to a specific URL, extracts product information from a wishlist table, and processes the purchases while handling dialog events.

Changes

File Change Summary
daily-challenges/2024-10/26/khanh5923_26.spec.ts - Added Product interface with name and qnt properties
- Implemented buyProduct function for purchasing products
- Created test case "khanh5923_26" with product purchase logic

Sequence Diagram

sequenceDiagram
    participant Test as Test Case
    participant Page as Playwright Page
    participant BuyProduct as buyProduct Function
    
    Test->>Page: Navigate to URL
    Test->>Page: Extract product list
    Test->>BuyProduct: Call with product list and page
    
    loop For each product
        BuyProduct->>Page: Check product visibility
        alt Product visible
            BuyProduct->>Page: Click purchase button
        else Product not visible
            BuyProduct->>Page: Add to secondary list
            BuyProduct->>Page: Click pagination
            BuyProduct->>BuyProduct: Recursive call
        end
    end
    
    Test->>Page: Handle dialog events
    Test->>Page: Verify purchase result
Loading

Possibly related PRs

Suggested reviewers

  • minhphong306

Poem

🐰 Clicking buttons with playwright's might,
Products dance into the shopping light!
Pagination's magic, a recursive delight,
Purchasing dreams with algorithmic flight.
Test case complete, success shines bright! 🛒

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1fec4cf and 9ee47aa.

📒 Files selected for processing (1)
  • daily-challenges/2024-10/26/khanh5923_26.spec.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
daily-challenges/2024-10/26/khanh5923_26.spec.ts

[error] 11-11: Forbidden non-null assertion.

(lint/style/noNonNullAssertion)


[error] 7-7: This let declares a variable that is only assigned once.

'productSecondtList' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 33-33: This let declares a variable that is only assigned once.

'productsList' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

Comment on lines +17 to +21
for (let i = 1; i <= Number(product.qnt); i++) {
await page.waitForTimeout(10);
await page.locator(`//div[contains(text(),'${product.name}')]/following-sibling::div//button[2]`).click();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Optimize the quantity-based click loop

Regarding your concern about the for loop, there are several ways to improve this:

  1. Use Playwright's built-in click({ clickCount: n }) instead of multiple clicks
  2. Consider using evaluate() to directly set the quantity value if there's an input field
// Option 1: Use clickCount
await page.locator(`//div[contains(text(),'${product.name}')]/following-sibling::div//button[2]`)
  .click({ clickCount: Number(product.qnt) });

// Option 2: If there's an input field, you could try:
await page.evaluate((selector, value) => {
  const input = document.querySelector(selector);
  if (input) {
    Object.defineProperty(input, 'readonly', { value: false });
    input.value = value;
  }
}, 'quantity-input-selector', product.qnt);

Comment on lines +10 to +15
try {
await expect(page.locator(`//div[contains(text(),'${product.name}')]`)).toHaveText(product.name!);
visible = true;
} catch {
productSecondtList.push(product);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling and selector reliability

The current error handling silently catches all errors and the XPath selectors are brittle.

  1. Use more reliable selectors (data-testid, role, etc.)
  2. Add specific error handling
  3. Add logging for debugging
try {
  const productElement = page.getByTestId(`product-${product.name}`);
  await expect(productElement).toBeVisible({ timeout: 5000 });
  visible = true;
} catch (error) {
  console.log(`Product ${product.name} not visible on current page: ${error.message}`);
  productSecondList.push(product);
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 11-11: Forbidden non-null assertion.

(lint/style/noNonNullAssertion)

Comment on lines +34 to +39
for (let i = 1; i <= 5; i++) {
productsList.push({
name: await page.locator(`//tbody[@id="wishlist"]//tr[${i}]//td[1]`).textContent(),
qnt: await page.locator(`//tbody[@id="wishlist"]//tr[${i}]//td[2]`).textContent(),
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove hardcoded product count

The hardcoded loop count of 5 makes the test brittle. Instead, get the actual row count dynamically.

const rows = await page.locator('//tbody[@id="wishlist"]//tr').count();
for (let i = 1; i <= rows; i++) {
  // ... rest of the code
}

Comment on lines +41 to +46
page.on("dialog", async (dialog) => {
const messageResult = dialog.message();
await dialog.accept();
expect(messageResult).toContain('Bạn đã đi chợ chính xác!');
});
await page.click(`//button[@class='check-result']`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Move dialog handler setup before triggering actions

The dialog handler should be set up before any actions that might trigger dialogs to ensure no dialogs are missed.

Move this block before the buyProduct call:

// Move this before line 40
page.on("dialog", async (dialog) => {
  const messageResult = dialog.message();
  await dialog.accept();
  expect(messageResult).toContain('Bạn đã đi chợ chính xác!');
});

Comment on lines +1 to +47
import { test, expect, Page } from "@playwright/test";
interface Product {
name: string | null;
qnt: string | null;
}
async function buyProduct(productsList: Product[], page: Page): Promise<void> {
let productSecondtList:Product[] = [];
for (const product of productsList) {
let visible = false;
try {
await expect(page.locator(`//div[contains(text(),'${product.name}')]`)).toHaveText(product.name!);
visible = true;
} catch {
productSecondtList.push(product);
}
if (visible) {
for (let i = 1; i <= Number(product.qnt); i++) {
await page.waitForTimeout(10);
await page.locator(`//div[contains(text(),'${product.name}')]/following-sibling::div//button[2]`).click();
}
}
}
if (productSecondtList.length > 0) {
await page.click(`//div[@class="pagination"]//button[2]`);
await buyProduct(productSecondtList, page);
}
else return;
}

test.setTimeout(60000);
test("khanh5923_26", async ({ page }) => {
await page.goto(`https://material.playwrightvn.com/games/001-di-cho.html`);
let productsList:Product[] = [];
for (let i = 1; i <= 5; i++) {
productsList.push({
name: await page.locator(`//tbody[@id="wishlist"]//tr[${i}]//td[1]`).textContent(),
qnt: await page.locator(`//tbody[@id="wishlist"]//tr[${i}]//td[2]`).textContent(),
});
}
await buyProduct(productsList, page);
page.on("dialog", async (dialog) => {
const messageResult = dialog.message();
await dialog.accept();
expect(messageResult).toContain('Bạn đã đi chợ chính xác!');
});
await page.click(`//button[@class='check-result']`);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider implementing Page Object Model pattern

To improve maintainability and reusability, consider:

  1. Implementing the Page Object Model pattern
  2. Moving selectors to a separate configuration file
  3. Creating reusable test utilities for common operations

Would you like me to provide an example of how to restructure this using the Page Object Model pattern?

🧰 Tools
🪛 Biome (1.9.4)

[error] 11-11: Forbidden non-null assertion.

(lint/style/noNonNullAssertion)


[error] 7-7: This let declares a variable that is only assigned once.

'productSecondtList' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 33-33: This let declares a variable that is only assigned once.

'productsList' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

Comment on lines +2 to +5
interface Product {
name: string | null;
qnt: string | null;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider strengthening the type definitions

The nullable fields in the Product interface could lead to runtime errors. Consider making these fields required since they appear to be essential for the functionality.

 interface Product {
-  name: string | null;
-  qnt: string | null;
+  name: string;
+  qnt: string;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface Product {
name: string | null;
qnt: string | null;
}
interface Product {
name: string;
qnt: string;
}

qnt: string | null;
}
async function buyProduct(productsList: Product[], page: Page): Promise<void> {
let productSecondtList:Product[] = [];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Fix typo in variable name

The variable name contains a typo: productSecondtList should be productSecondList.

-  let productSecondtList:Product[] = [];
+  const productSecondList: Product[] = [];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let productSecondtList:Product[] = [];
const productSecondList: Product[] = [];
🧰 Tools
🪛 Biome (1.9.4)

[error] 7-7: This let declares a variable that is only assigned once.

'productSecondtList' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

}
if (visible) {
for (let i = 1; i <= Number(product.qnt); i++) {
await page.waitForTimeout(10);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove hardcoded timeout

Hardcoded timeouts are unreliable and can make tests flaky. Instead, wait for specific conditions.

-      await page.waitForTimeout(10);
+      await page.waitForSelector(`//div[contains(text(),'${product.name}')]/following-sibling::div//button[2]`, { state: 'attached' });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await page.waitForTimeout(10);
await page.waitForSelector(`//div[contains(text(),'${product.name}')]/following-sibling::div//button[2]`, { state: 'attached' });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant