Skip to content

feat: add tests for shouldRunVsCodeCli and bindAddrFromArgs #4211

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

Merged
merged 3 commits into from
Sep 21, 2021

Conversation

jsjoeio
Copy link
Contributor

@jsjoeio jsjoeio commented Sep 20, 2021

This PR adds more tests for src/node/cli.ts. Specifically, these functions: shouldRunVsCodeCli and bindAddrFromArgs

Fixes #4210

TODOS

  • shouldRunVsCodeCli
  • bindAddrFromArgs
  • fix broken tests? (it seems one test is broken locally for me, probably a local issue)

@jsjoeio jsjoeio self-assigned this Sep 20, 2021
@jsjoeio jsjoeio added the testing Anything related to testing label Sep 20, 2021
@jsjoeio jsjoeio changed the title Jsjoeio-add-moar-tests feat: add tests for shouldRunVsCodeCli and bindAddrFromArgs Sep 20, 2021
@codecov
Copy link

codecov bot commented Sep 20, 2021

Codecov Report

Merging #4211 (d921829) into main (92d0d28) will increase coverage by 0.14%.
The diff coverage is 100.00%.

❗ Current head d921829 differs from pull request most recent head f847575. Consider uploading reports for the commit f847575 to get more accurate results
Impacted file tree graph

@@            Coverage Diff             @@
##             main    #4211      +/-   ##
==========================================
+ Coverage   64.94%   65.09%   +0.14%     
==========================================
  Files          36       36              
  Lines        1880     1882       +2     
  Branches      381      380       -1     
==========================================
+ Hits         1221     1225       +4     
+ Misses        560      559       -1     
+ Partials       99       98       -1     
Impacted Files Coverage Δ
src/node/cli.ts 80.99% <100.00%> (+0.99%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 92d0d28...f847575. Read the comment docs.

@github-actions
Copy link

github-actions bot commented Sep 20, 2021

✨ Coder.com for PR #4211 deployed! It will be updated on every commit.

@jsjoeio
Copy link
Contributor Author

jsjoeio commented Sep 20, 2021

I'm a bit dumbfounded. The tests pass in CI: https://github.com/cdr/code-server/pull/4211/checks?check_run_id=3657430012

But 1 test is not passing locally 🤔 It's the should catch errors thrown when unlinking a socket test.

 it("should catch errors thrown when unlinking a socket", async () => {
    const tmpDir2 = await tmpdir("unlink-socket-error")
    const tmpFile = path.join(tmpDir2, "unlink-socket-file")
    // await promises.writeFile(tmpFile, "")
    const socketPath = tmpFile
    const defaultArgs = await setDefaults({
      _: [],
      socket: socketPath,
    })

    const app = await createApp(defaultArgs)
    const server = app[2]

    expect(spy).toHaveBeenCalledTimes(1)
    expect(spy).toHaveBeenCalledWith(`ENOENT: no such file or directory, unlink '${socketPath}'`)

    server.close()
    // Ensure directory was removed
    rmdirSync(tmpDir2, { recursive: true })
  })

Basically, what's happening is:

  • I pass in a path to a file that doesn't exist for socket
  • It tries to unlink the file
  • Then it should call the spy (which is our logger), to log the error

BUT it does all this but then gets to server.listen and instead throws and error saying "address already in use:

See below:

      try {
        await fs.unlink(args.socket)
      } catch (error: any) {
        handleArgsSocketCatchError(error)
      }
      server.listen(args.socket, resolve

image

image

@jsjoeio
Copy link
Contributor Author

jsjoeio commented Sep 20, 2021

help @code-asher - any ideas?

* This function creates the bind address
* using the CLI args.
*/
export function bindAddrFromArgs(addr: Addr, args: Args): Addr {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

🛠️ Exported so that we can unit test. Added short description for good measure.

Choose a reason for hiding this comment

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

Cool!

src/node/cli.ts Outdated
Comment on lines 629 to 644
return !!args["list-extensions"] || !!args["install-extension"] || !!args["uninstall-extension"]
// Create new interface with only these keys
// Pick<Args, "list-extensions" | "install-extension" | "uninstall-extension">
// Get the keys of new interface
// keyof ...
// Turn that into an array
// Array<...>
type ExtensionArgs = Array<keyof Pick<Args, "list-extensions" | "install-extension" | "uninstall-extension">>
const extensionRelatedArgs: ExtensionArgs = ["list-extensions", "install-extension", "uninstall-extension"]

const argKeys = Object.keys(args)

// If any of the extensionRelatedArgs are included in args
// then we don't want to run the vscode cli
return extensionRelatedArgs.some((arg) => argKeys.includes(arg))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

🔁 Refactored this function.

"But isn't this code more verbose?"

"Yes, but here's why I think it's an improvement:

  • !! is a clever technique in JS to cast a value to a Boolean, but it's hard to read.
  • previously these were hard-coded values, which means they weren't tied to the Args type they're based off

Now we have:

  • clear comments explaining what's happening
  • type-safety because the args we check for are now based on the Args type so if those change, TS will complain and we'll catch that here"

Happy to revert the change if we think this function should be left as it was!

@jsjoeio jsjoeio marked this pull request as ready for review September 21, 2021 17:47
@jsjoeio jsjoeio requested a review from a team as a code owner September 21, 2021 17:47
src/node/cli.ts Outdated
// keyof ...
// Turn that into an array
// Array<...>
type ExtensionArgs = Array<keyof Pick<Args, "list-extensions" | "install-extension" | "uninstall-extension">>

Choose a reason for hiding this comment

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

I like the overall strategy to make this type-safe and get the benefit from the compiler! The only thing I find a bit awkward is that we have to reference the "list-extensions" | "install-extensions" | "uninstall-extensions" twice here.

I wonder if we could get most of the benefits, without having to define these multiple times, by doing:

type ArgumentKeys = Array<keyof Args>;
const extensionRelatedArgs: ArgumentKeys = ["list-extensions", "install-extension", "uninstall-extension"];

That way - the compiler will still flag an error if these get out-of-sync, but you only have to define them once here in shouldRunVsCodeCli

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh this is a huge improvement. Waaaaay better. Didn't think about that. Thanks for providing this suggestion! I'll incorporate this suggestion before merging! 🙌

})

it("should use the args.port over process.env.PORT if both set", () => {
const [setValue, resetValue] = useEnv("PORT")

Choose a reason for hiding this comment

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

Nice set of tests 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks!

Copy link

@bryphe-coder bryphe-coder left a comment

Choose a reason for hiding this comment

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

Looks great to me - nice work @jsjoeio ! I like your approach to leveraging the TS type system as much as possible.

Just had minor feedback about streamlining having to define the "list-extensions" | "install-extension" | "uninstall-extension". Up to you if you want to incorporate that or not 👍

@jsjoeio jsjoeio force-pushed the jsjoeio-add-moar-tests branch from 541b3cc to f847575 Compare September 21, 2021 18:48
@jsjoeio jsjoeio enabled auto-merge September 21, 2021 18:51
@jsjoeio jsjoeio merged commit e8063c7 into main Sep 21, 2021
@jsjoeio jsjoeio deleted the jsjoeio-add-moar-tests branch September 21, 2021 18:55
Copy link
Contributor

@greyscaled greyscaled left a comment

Choose a reason for hiding this comment

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

✔️ Nice work!

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

Successfully merging this pull request may close these issues.

Add tests for shouldRunVsCodeCli and bindAddrFromArgs
3 participants