Kraigie / nostrum

Elixir Discord Library
https://kraigie.github.io/nostrum/
MIT License
622 stars 129 forks source link

How do you test bots with this library? #250

Open therealjasonkenney opened 3 years ago

therealjasonkenney commented 3 years ago

I can't seem to find anything in the documentation to configure nostrum to NOT spin up and connect to discord when running tests for the code. I tried dev: true. but it seemed to do nothing.

I do not want to be using a real discord token in a test environment.

Kraigie commented 3 years ago

The dev: true option is solely for if you want to run nostrum as it's own application.

If you do not want to supply a token in the test environment you have options. You could run the tests with mix test --no-start which would prevent any applications from starting. You could also just prevent just nostrum from starting in tests like is outlined here: https://github.com/Kraigie/nostrum/issues/230. Unfortunately I think your options besides this are pretty limited because of how the library is currently structured.

These aren't nostrum-specific constructs, they're provided at the language level. That said I think it would probably be prudent to include a reminder in the nostrum docs somewhere because this question has cropped up in the past, so thanks for that!

bdanklin commented 3 years ago

Just wanted to add my thoughts on this after myself and @jchristgit both mentioned it inside #309 where it is slightly off-topic.

My idea is to implement a testing bot for running mix test. The required environment variables could be held inside GitHub so that the tests could be run by anyone when initiating a PR to the upstream repo without providing direct access to the bot. As well as locally by providing my own test bot/server variables.

#doctest_helpers.ex
defmodule DoctestHelpers do
  def doctest_server_id()
    System.get_env("DEV_SERVER_ID")
  end
end
#nostrum.api.ex
import DoctestHelpers

  @doc """
  Gets a list of guild channels.

  ## Examples

      iex> Nostrum.Api.get_guild_channels(doctest_server_id)
      {:ok, [%Nostrum.Struct.Channel{guild_id: ^doctest_server_id} | _]}

  """

  @doc """
  Creates a channel for a guild.

  ## Examples

    iex> Nostrum.Api.create_guild_channel(doctest_server_id, name: "elixir-nostrum", topic: "craig's domain")
    {:ok, %Nostrum.Struct.Channel{guild_id: ^doctest_server_id}}

  """

This has the downside of making the documentation less readable. So a solution that covers that would be to replace all instances of these helpers with a dummy value when creating the documentation. This is a bit of a pain, but I believe would be worth it, if it gives you functional doctests without all the setup/teardown/hardcoded values.