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

test: add test on restart and dev command #34

Merged

Conversation

zulkhair
Copy link
Collaborator

@zulkhair zulkhair commented Feb 4, 2024

Closes: WORLD-532

Overview

Add test for restart and dev command

Brief Changelog

  • Add Detach mode for restart
  • Modify older test, adding restart before stop and purge
  • Add new test for dev

Testing and Verifying

  • Running the unit test suite

Summary by CodeRabbit

  • New Features
    • Added a new --detach flag for the restart command to enable running in detached mode.
  • Tests
    • Enhanced testing suite with additional health checks and a new development mode test.
  • Refactor
    • Updated test names and logic to incorporate restart functionality.

Copy link

graphite-app bot commented Feb 4, 2024

Your org has enabled the Graphite merge queue for merging into main

Add the label “graphite/merge” to the PR and Graphite will automatically add it to the merge queue when it’s ready to merge.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

Copy link

coderabbitai bot commented Feb 4, 2024

Walkthrough

The recent updates introduce a new --detach flag for the restartCmd command, enhancing the Cardinal game shard stack by enabling detached mode operations. Additionally, the testing framework under cmd/world/root sees significant improvements with the introduction of a new import, a health response structure, a dedicated health check function, and an extended test case TestCreateStartStopRestartPurge that incorporates restart logic and health checks. A new test function, TestDev, is also added to facilitate development mode testing, complete with health checks and shutdown procedures.

Changes

Files Summary
cmd/world/cardinal/restart.go Added --detach flag to restartCmd for detached mode operations.
cmd/world/root/root_test.go Added import, healthResponse struct, getHealthCheck function, updated and added tests.

🐇✨
In the world of code, where changes abound,
A little rabbit hopped, making barely a sound.
With a flick and a click, new paths were found,
In the tests and the flags, where progress is crowned.
🌟🚀

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>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link
Collaborator Author

zulkhair commented Feb 4, 2024

Current dependencies on/for this PR:

This stack of pull requests is managed by Graphite.

@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from 33a011f to 94866b1 Compare February 4, 2024 13:37
@zulkhair zulkhair force-pushed the daim/world-757-add_hot_reloading_on_dev_mode branch from 04487c0 to 94b6df6 Compare February 4, 2024 15:00
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch 2 times, most recently from a29ee6c to 938db8d Compare February 4, 2024 15:05
Copy link

codecov bot commented Feb 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Comparison is base (125ed24) 47.97% compared to head (4e86b62) 47.97%.

❗ Current head 4e86b62 differs from pull request most recent head 4a0ac1e. Consider uploading reports for the commit 4a0ac1e to get more accurate results

Additional details and impacted files
@@           Coverage Diff           @@
##             main      #34   +/-   ##
=======================================
  Coverage   47.97%   47.97%           
=======================================
  Files           8        8           
  Lines         469      469           
=======================================
  Hits          225      225           
  Misses        229      229           
  Partials       15       15           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@zulkhair zulkhair marked this pull request as ready for review February 5, 2024 12:17
@zulkhair zulkhair requested a review from a team February 5, 2024 12:17
@zulkhair zulkhair force-pushed the daim/world-757-add_hot_reloading_on_dev_mode branch 2 times, most recently from c95b668 to 66b2b6f Compare February 6, 2024 13:14
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from 938db8d to 641c402 Compare February 6, 2024 13:20
@zulkhair zulkhair force-pushed the daim/world-757-add_hot_reloading_on_dev_mode branch from 66b2b6f to bcb810b Compare February 6, 2024 13:22
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from 641c402 to b627701 Compare February 6, 2024 13:22
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
cmd/world/root/root_test.go Outdated Show resolved Hide resolved
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from b627701 to e3d993c Compare February 7, 2024 10:05
@zulkhair zulkhair force-pushed the daim/world-757-add_hot_reloading_on_dev_mode branch from bcb810b to 125ed24 Compare February 7, 2024 10:26
@zulkhair zulkhair changed the base branch from daim/world-757-add_hot_reloading_on_dev_mode to main February 7, 2024 10:28
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from e3d993c to 4e86b62 Compare February 7, 2024 10:36
Copy link

graphite-app bot commented Feb 7, 2024

Merge activity

Closes: WORLD-532

## Overview

Add test for `restart` and `dev` command

## Brief Changelog

- Add Detach mode for restart
- Modify older test, adding restart before stop and purge
- Add new test for dev

## Testing and Verifying

- Running the unit test suite
@zulkhair zulkhair force-pushed the daim/world-532-add_test_on_restart_and_dev_command branch from 4e86b62 to 4a0ac1e Compare February 7, 2024 17:54
@graphite-app graphite-app bot merged commit 4a0ac1e into main Feb 7, 2024
5 checks passed
Copy link

@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.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 125ed24 and 4a0ac1e.
Files selected for processing (2)
  • cmd/world/cardinal/restart.go (2 hunks)
  • cmd/world/root/root_test.go (3 hunks)
Additional comments: 3
cmd/world/cardinal/restart.go (1)
  • 16-16: Ensure the flagDetach variable is defined and correctly scoped within the package or globally if intended for reuse.
cmd/world/root/root_test.go (2)
  • 12-12: The import of pkg.world.dev/world-cli/cmd/world/cardinal is added. Verify its usage within this test file to ensure it's necessary, as direct code references to the cardinal package are not visible in the provided code segments.
  • 18-38: The healthResponse struct and getHealthCheck function are well-defined for checking the health of the application. Ensure the health check endpoint (http://127.0.0.1:3333/health) matches the application's actual health check URL and is not hardcoded for testing environments.

Comment on lines +41 to +42
if replaceBoolWithFlag(cmd, flagDetach, &cfg.Detach); err != nil {
return err
Copy link

Choose a reason for hiding this comment

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

The error handling for replaceBoolWithFlag does not capture the specific error from the function call due to shadowing err from the outer scope. Consider assigning the error to a new variable or directly returning it without assignment.

- if replaceBoolWithFlag(cmd, flagDetach, &cfg.Detach); err != nil {
+ if err := replaceBoolWithFlag(cmd, flagDetach, &cfg.Detach); err != nil {

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.

Suggested change
if replaceBoolWithFlag(cmd, flagDetach, &cfg.Detach); err != nil {
return err
if err := replaceBoolWithFlag(cmd, flagDetach, &cfg.Detach); err != nil {
return err

Comment on lines 146 to 253
IsGameLoopRunning bool
}
err = json.NewDecoder(resp.Body).Decode(&healthResponse)
assert.Assert(t, resp.IsServerRunning)
assert.Assert(t, resp.IsGameLoopRunning)

// Restart cardinal
rootCmd.SetArgs([]string{"cardinal", "restart", "--detach"})
err = rootCmd.Execute()
assert.NilError(t, err)

// Check cardinal health after restart
resp, err = getHealthCheck()
assert.NilError(t, err)
assert.Assert(t, healthResponse.IsServerRunning)
assert.Assert(t, healthResponse.IsGameLoopRunning)
assert.Equal(t, resp.StatusCode, 200)
assert.Assert(t, resp.IsServerRunning)
assert.Assert(t, resp.IsGameLoopRunning)

// Stop cardinal
rootCmd.SetArgs([]string{"cardinal", "stop"})
err = rootCmd.Execute()
assert.NilError(t, err)

// Check cardinal health
_, err = http.Get("http://127.0.0.1:3333/health")
// Check cardinal health (expected error)
_, err = getHealthCheck()
assert.Error(t, err,
"Get \"http://127.0.0.1:3333/health\": dial tcp 127.0.0.1:3333: connect: connection refused")
}

// Purge cardinal
rootCmd.SetArgs([]string{"cardinal", "purge"})
err = rootCmd.Execute()
func TestDev(t *testing.T) {
// Create Cardinal
gameDir, err := os.MkdirTemp("", "game-template")
assert.NilError(t, err)

// Remove dir
defer func() {
err = os.RemoveAll(gameDir)
assert.NilError(t, err)
}()

// Change dir
err = os.Chdir(gameDir)
assert.NilError(t, err)

//set tea ouput to variable
teaOut := &bytes.Buffer{}
createCmd := getCreateCmd(teaOut)
createCmd.SetArgs([]string{gameDir})

err = createCmd.Execute()
assert.NilError(t, err)

// Start cardinal dev
rootCmd.SetArgs([]string{"cardinal", "dev"})
go func() {
err := rootCmd.Execute()
assert.NilError(t, err)
}()

// Check cardinal health for 300 second, waiting to download dependencies and building the apps
isServerRunning := false
isGameLoopRunning := false
timeout := time.Now().Add(300 * time.Second)
for !(isServerRunning && isGameLoopRunning) && time.Now().Before(timeout) {
resp, err := getHealthCheck()
if err != nil {
time.Sleep(1 * time.Second)
continue
}
assert.Equal(t, resp.StatusCode, 200)
isServerRunning = resp.IsServerRunning
isGameLoopRunning = resp.IsGameLoopRunning
}
assert.Assert(t, isServerRunning)
assert.Assert(t, isGameLoopRunning)

// Shutdown the program
close(cardinal.StopChan)

// Check cardinal health (expected error), trying for 10 times
count := 0
for count < 10 {
_, err = getHealthCheck()
if err != nil {
break
}
time.Sleep(1 * time.Second)
count++
}

assert.Error(t, err,
"Get \"http://127.0.0.1:3333/health\": dial tcp 127.0.0.1:3333: connect: connection refused")
}
Copy link

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [125-188]

The test TestCreateStartStopRestartPurge correctly follows the lifecycle of creating, starting, restarting, and purging the application. However, ensure that the health check assertions (assert.Equal(t, resp.StatusCode, 200)) are robust enough to handle transient states or delays in service availability, especially after restart operations.

Consider adding retries with backoff for health checks to handle transient failures.

Comment on lines +190 to +252
func TestDev(t *testing.T) {
// Create Cardinal
gameDir, err := os.MkdirTemp("", "game-template")
assert.NilError(t, err)

// Remove dir
defer func() {
err = os.RemoveAll(gameDir)
assert.NilError(t, err)
}()

// Change dir
err = os.Chdir(gameDir)
assert.NilError(t, err)

//set tea ouput to variable
teaOut := &bytes.Buffer{}
createCmd := getCreateCmd(teaOut)
createCmd.SetArgs([]string{gameDir})

err = createCmd.Execute()
assert.NilError(t, err)

// Start cardinal dev
rootCmd.SetArgs([]string{"cardinal", "dev"})
go func() {
err := rootCmd.Execute()
assert.NilError(t, err)
}()

// Check cardinal health for 300 second, waiting to download dependencies and building the apps
isServerRunning := false
isGameLoopRunning := false
timeout := time.Now().Add(300 * time.Second)
for !(isServerRunning && isGameLoopRunning) && time.Now().Before(timeout) {
resp, err := getHealthCheck()
if err != nil {
time.Sleep(1 * time.Second)
continue
}
assert.Equal(t, resp.StatusCode, 200)
isServerRunning = resp.IsServerRunning
isGameLoopRunning = resp.IsGameLoopRunning
}
assert.Assert(t, isServerRunning)
assert.Assert(t, isGameLoopRunning)

// Shutdown the program
close(cardinal.StopChan)

// Check cardinal health (expected error), trying for 10 times
count := 0
for count < 10 {
_, err = getHealthCheck()
if err != nil {
break
}
time.Sleep(1 * time.Second)
count++
}

assert.Error(t, err,
"Get \"http://127.0.0.1:3333/health\": dial tcp 127.0.0.1:3333: connect: connection refused")
Copy link

Choose a reason for hiding this comment

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

The TestDev function introduces a test for the development mode, including asynchronous execution and health checks. Ensure that the asynchronous execution pattern (go func() { ... }()) is correctly synchronized with the test's main goroutine to prevent premature test termination or flaky test results.

Implement a more reliable synchronization mechanism, such as using sync.WaitGroup or channels, to ensure the test waits for the asynchronous operation to complete before proceeding with assertions.

@zulkhair zulkhair deleted the daim/world-532-add_test_on_restart_and_dev_command branch May 30, 2024 02:25
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.

2 participants