Skip to content
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

feat: tests for game selection #198

Merged
merged 2 commits into from
Oct 20, 2024
Merged

Conversation

williamsjokvist
Copy link
Owner

@williamsjokvist williamsjokvist commented Oct 20, 2024

Not much worth in testing this atm but just to get some tests going in the repo.

Added in memory db in tests so we can call the storage layer to make assertions that matches were stored etc.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling in the Authenticate method to check for browser initialization.
    • Improved configuration options for the tracking handler.
  • Bug Fixes

    • Updated test cases for better error message handling during game selection.
  • Chores

    • Modified SQL storage initialization to support in-memory database configuration.
    • Adjusted error handling in test setup for improved visibility.

Copy link
Contributor

coderabbitai bot commented Oct 20, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several modifications across multiple files, primarily affecting the initialization and configuration of storage and handlers. Key changes include updates to the TestMain function signature, improvements in error handling, and the introduction of a new configuration structure for the trackingHandler. Additionally, the SQL storage initialization has been altered to accept a boolean parameter, enhancing the flexibility of database configuration. The changes aim to improve error visibility and robustness in various components of the application.

Changes

File Change Summary
cmd/init_test.go - Updated TestMain function signature from *testing.T to *testing.M.
- Modified SQL storage initialization to include a boolean argument.
- Changed error handling from t.Fatal to log.Fatalf.
- Introduced a new config.Config structure for cmd.NewTrackingHandler.
cmd/tracking_test.go - Updated TestTrackingSelectGame to include an expErrMsg field in test cases.
- Utilized t.Run for better organization of test cases and error handling.
main.go - Altered SQL storage initialization to pass a boolean argument to sql.NewStorage().
pkg/storage/sql/storage.go - Updated NewStorage function to accept a boolean parameter, useInMemoryDb, affecting database connection logic.
pkg/tracker/sf6/cfn/client.go - Enhanced Authenticate method to check if browser is initialized before proceeding.

Possibly related PRs

Suggested reviewers

  • tifye

🐇 "In the code we hop and play,
With tests and handlers on display.
A boolean here, a log there,
Our functions dance with utmost care.
Through SQL and tracking, we refine,
In this rabbit's burrow, all aligns!" 🐇


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 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
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: 3

🧹 Outside diff range and nitpick comments (5)
cmd/tracking_test.go (2)

11-28: Improved test structure with clear expectations.

The updated test structure with the expErrMsg field provides more clarity on expected outcomes for each test case. The test cases cover different scenarios, including successful game selection and error cases, which is good for comprehensive testing.

Consider adding a comment above the tests slice to briefly explain the purpose of these test cases and the fields in the struct. This can enhance readability and maintainability.


32-40: Improved test execution with better error handling.

The use of t.Run for each test case enhances test organization and reporting. The updated error handling logic provides more precise checking by comparing actual error messages with expected ones.

Consider using a helper function for error checking to reduce duplication and improve readability. For example:

func assertError(t *testing.T, got error, want string) {
    t.Helper()
    if (got == nil) != (want == "") {
        t.Errorf("unexpected error status: got %v, want %v", got, want)
        return
    }
    if got != nil && got.Error() != want {
        t.Errorf("unexpected error message: got %q, want %q", got.Error(), want)
    }
}

Then use it in your tests:

assertError(t, err, tt.expErrMsg)
pkg/storage/sql/storage.go (1)

26-26: Suggestion: Add documentation for the new parameter

Consider adding a comment to document the useInMemoryDb parameter, explaining its purpose and expected values. This will improve code readability and maintainability.

Example:

// NewStorage initializes and returns a new Storage instance.
// If useInMemoryDb is true, an in-memory SQLite database is used;
// otherwise, a file-based database is created using the path from getDataSource().
func NewStorage(useInMemoryDb bool) (*Storage, error) {
pkg/tracker/sf6/cfn/client.go (1)

64-69: Approve changes with a minor suggestion for consistency

The addition of the browser initialization check is a valuable improvement to the Authenticate method. It prevents potential nil pointer dereferences and aligns with the PR's objective of enhancing error handling.

For consistency with the rest of the method, consider updating the error handling as follows:

 if t.browser == nil {
-		statChan <- *status.WithError(fmt.Errorf("browser not initialized"))
+		status.Err = fmt.Errorf("browser not initialized")
+		statChan <- *status
 		return
 }

This change makes the error handling consistent with other parts of the method where status.Err is set directly.

cmd/init_test.go (1)

33-39: Avoid hardcoding credentials in code

Hardcoding credentials like CapIDEmail and CapIDPassword directly in the code, even in tests, is not recommended. This practice can lead to security vulnerabilities if the code is ever exposed.

Consider using environment variables or a secure configuration management system to provide these values. For example:

 cfg := config.Config{
 	AppVersion:        "4.0.0",
 	Headless:          true,
-	CapIDEmail:        "test",
-	CapIDPassword:     "test",
+	CapIDEmail:        os.Getenv("CAP_ID_EMAIL"),
+	CapIDPassword:     os.Getenv("CAP_ID_PASSWORD"),
 	BrowserSourcePort: 4242,
 }

Ensure to import the "os" package if you implement this change:

 import (
 	"fmt"
+	"os"
 	"log"
 	"testing"
 )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 028edb4 and 83d7615.

📒 Files selected for processing (5)
  • cmd/init_test.go (2 hunks)
  • cmd/tracking_test.go (1 hunks)
  • main.go (1 hunks)
  • pkg/storage/sql/storage.go (1 hunks)
  • pkg/tracker/sf6/cfn/client.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
pkg/storage/sql/storage.go (2)

26-26: Approve: Flexible database initialization

The addition of the useInMemoryDb parameter enhances the flexibility of the NewStorage function, allowing for both file-based and in-memory database initialization. This change aligns well with the PR objectives of adding tests, as in-memory databases are particularly useful for testing scenarios.


30-34: Verify: Impact on existing code

The changes to the NewStorage function signature may affect other parts of the codebase that call this function. Let's verify that all calls to NewStorage have been updated accordingly.

✅ Verification successful

Verified: All calls to NewStorage have been updated with the new function signature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any calls to NewStorage that haven't been updated

# Test: Search for NewStorage calls without boolean argument
rg 'NewStorage\(\s*\)' --type go

Length of output: 352


Script:

#!/bin/bash
# Description: Check for any calls to sql.NewStorage that haven't been updated

# Test: Search for sql.NewStorage calls without the new arguments
rg 'sql\.NewStorage\(\s*\)' --type go

Length of output: 136

pkg/tracker/sf6/cfn/client.go (1)

64-69: Overall impact: Improved robustness without altering core functionality

The addition of the browser initialization check at the beginning of the Authenticate method enhances the robustness of the function without changing its core behavior. This non-breaking change aligns well with the PR's objectives of improving error handling and is consistent with good coding practices.

The rest of the method and file remain unchanged, indicating a focused and purposeful modification. This change reduces the risk of runtime errors due to uninitialized browser instances, contributing to the overall stability of the authentication process.

main.go (2)

Line range hint 1-254: Overall, the file structure and initialization logic look good.

The change to NewStorage is the only modification in this file, but it's a valuable addition that enhances the application's flexibility, particularly for testing scenarios. The rest of the file maintains good structure and initialization practices for the application.


135-135: LGTM! Consider verifying other NewStorage calls.

The change to sql.NewStorage(false) aligns with the updated function signature and supports the PR objective of adding tests. This modification allows for flexible database configuration, which is beneficial for testing scenarios.

To ensure consistency across the codebase:

  1. Verify other occurrences of NewStorage calls:

  2. If there are other occurrences, make sure they are updated accordingly.

Consider updating the function documentation for NewStorage in the sql package to reflect the new boolean parameter and its purpose.

cmd/tracking_test.go Show resolved Hide resolved
cmd/init_test.go Outdated Show resolved Hide resolved
cmd/init_test.go Outdated Show resolved Hide resolved
@williamsjokvist williamsjokvist merged commit f5c57ad into master Oct 20, 2024
2 checks passed
@williamsjokvist williamsjokvist deleted the feat/select-game-tests branch October 20, 2024 14:57
@coderabbitai coderabbitai bot mentioned this pull request Nov 5, 2024
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