Writing unit test for a module which takes in inputs from other modules

Hi guys, I am working on writing unit tests for the terraform modules. I have explored both the Module Testing Experiment and apparentlymart/testing for unit testing.

While writing a unit test for a module which takes in inputs from other module, is it good to create the resources for other modules beforehand and pass the hard-coded value in the module being tested or create those resources for the other modules (calling those modules as well) in the unit test?

Example 1
Calling other modules within test.tf

module "logs" {
  source = "../../logs"
}

module "test" {
  source = "../"
 name = module.logs.name
}

OR

Example 2
Create the resources before for the logs module and pass the hard-coded value while calling the test module

module "main" {
  source = "../"
 name = "test-name"
}

Let me know if I am not clear with the examples shown above. Would be happy to discuss. @apparentlymart Can you please help on how it should be designed based on your testing framework

Hi @ankitakundra,

In the design of both of these mechanisms I was assuming that we’re always testing only one module at a time, not the combination of two modules at once. However, the testing configuration can in principle include any Terraform configuration you like, and so there’s no technical reason why you can’t call into some other module to produce some supporting infrastructure for the test.

The main difference between the two situations you showed here is the lifecycle of the “logs” objects. If you put a call to module "logs" inside the test configuration then the terraform test command will create the objects it declares, deal with the test assertions, and then automatically destroy the logging objects before completing the test run. If you instead apply the logs module outside and refer to it, the terraform test run will not create or destroy those logging objects, and so the test will only succeed if you’ve applied that module some other way before running terraform test.

Both of these approaches can be valid depending on your goals, though your Example 1 could result a more self-contained test because it declares all of the objects it depends on and so Terraform can temporarily deploy those only for the duration of the test, and clean them up again afterwards.

Hi @apparentlymart, thank you so much for the response, appreciate it.