Testing Singleton Resources
Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (34 / 80)
👈 Testing Periodic Actions | TOC | Testing Resiliency 👉
It’s quite common in Elixir and Erlang applications to have singleton resources. A singleton resource exists in your application as a single and unique unit. For example, a process with a globally registered name is a singleton resource, since no other process with that same name can exist in the system at the same time. That example is a bit oversimplified.
A more common and realistic example is a process that does something that should be done by at most one process at a time — for example, a process that needs exclusive access to a file on the file system or a process that periodically notifies users via SMS that it’s going to rain soon. See where we’re going with the latter? If we have more than one of this kind of process, we’re going to have a bad time because each of those processes will try to send text messages, resulting in users getting notified more than once. The solution could be to have a list of the notified users shared between the processes, for example in an ETS table. However, we’re just moving the problem around: the singleton resource is now the ETS table. Ouch. So, how do we test these scenarios?
We truly believe singletons often are one of the nastiest things to test. Writing singleton resources isn’t usually challenging, since you’ll have one instance of the resource running at any given time…