How to test code blocks, like doctest?

On a Hugo site with code blocks, I would like to be able to somehow test that code in an automated way. Specifically, I am talking about Go code, but the language does not really matter.

One way I can think of is to somehow make Hugo extract the code into separate files, potentially placed into functions the language’s test tool recognizes as tests. On these files, I could run the tests.
Maybe alternative output formats and code block rendering hooks could help here somehow?

Alternatively, the code could be in separate files and be drawn into the blocks on the site. This seems possible with readFile. However, each block needs its own file then I guess.

The first option would be way more author friendly. Can anybody hint me in a direction how this could be achieved?

Thanks!

Maybe, but you need to use the second option.

In my view, os.ReadFile and os.ReadDir are mostly legacy functions. Use this construct instead:

content/
β”œβ”€β”€ samples/
β”‚   └── sample-1/
β”‚       β”œβ”€β”€ foo_test.go
β”‚       └── index.md
└── _index.md

Then in a template/partial/shortcode do something like:

{{ with .Resources.Get "foo_test.go" }}
  {{ highlight .Content "go" }}
{{ end }}

Or set the lang by getting the file extension.

1 Like

Thanks @jmooring!
thank you for this hint!

Thinking about it a bit further, it may indeed be more flexible to do it with option 2. E.g., with some string functions application, it also allows to include only the relevant code in the code block, not potential boilerplate around it.

Will give this approach a try. Thanks again!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.