Is it possible to access context from within a doctest?

I’ve tried everything I can think of and haven’t been able to make this work. The challenge is that I’d like to initialize an Agent in the setup macro and have that Agent available to the doctests. Is this possible?

I do not know what you are able to think of, could you therefore show us what you have tried and what error you got?

AFAIK not possible, doctests are run in isolation and standalone, also an Agen implies a side effect, but:

In general, doctests are not recommended when your code examples contain side effects.

Here is a sample of what I am trying to do. The context created in MapAgentTest does not seem to be available within the doctests. Note that I would not have considered this to be a side-effect. Creating the Agents is required for each of the tests, which works if I write the redundant lines. I am trying to clean things up by doing it in one place, the setup macro.

 defmodule MapAgentTest do
  use ExUnit.Case, async: true

  setup context do
    {:ok, pid} = StatefulAgents.MapAgent.start
    Map.put(context, :pid, pid)
  end

  doctest StatefulAgents.MapAgent, import: true
end


defmodule MapAgent do
use Agent

@doc """
  iex> assert is_pid(context[:pid])
  true
"""
def start, do: Agent.start(fn -> %{} end)

@doc """
  iex> MapAgent.stop(context[:pid])
  :ok
"""
def stop(pid), do: Agent.stop(pid)

As a reader of your examples I’d be happy to actually see the setup as part of the example. This way I cant forget it has to be done…

Well, or write code that doesn’t produce that warning at all.


To actually answer your question…

No, there is no such way. I’m not sure if there is a reason other than, no one has asked so far, but to be honest, I prefer the way it is now, it follows “explicit is better than implicit”.

2 Likes

I think the way to think about @doctests is first of all to remember they are documentation. If the examples don’t add clarity to the documentation then they, in my opinion, should be in a normal .exs test suite.

Not knowing fully your intention I would say that the tests you plan don’t add clarity to the documentation and hence i would be confused to see them in the dockets.

3 Likes

Using the doctests as documentation is actually what is driving this. I have the tests working fine if I do all of the setup activities in each of the doctests, but repetitive setup in the doctests is ugly and I wanted to do it once in the setup macro. That doesn’t seem to be working out, so I guess I’ll go back to the old code that imports and starts an agent in every doctest, when all I wanted to document for each function was how to use that function. I hope this clarifies things.

Or just remove the iex> prefixes in those lines. That’s how e.g. ecto does handle that.

1 Like

So that they are just documentation and not actually ran as tests?

Yeah, e.g. Ecto.Changeset’s docs are full of those.

1 Like