So I've created a function which accepts an ID, internally queries a database via a repository from the data returned mutations are made to the data depending on different scenarios and then we return the data.
How would I unit test this function?
Would I stub the find method on my repository layer to return data so I'm not dependant on connecting on the database?
i will argue that you can only unit test code which is unit testable. my definition of unit testable code is code that exhibits these properties:
it gets everything it needs from its inputs
all its work is expressed through return values (or throwing exceptions)
it does not produce any side effects
the code you describe violates #1, by going to the database.
to answer your question directly, you would mock the database call and that mock would provide to your function expected data, such that you can mutate it and compare it to an expected output.
but i think the real right answer is to refactor your code, applying the Single Responsibility Principle. your code under test is doing two things (going to the database and mutating the result), instead of doing just one thing.
i would break out the database portion and assign that as Someone Else's Job. then your code under test could take that database result as an input, and its sole job would be to mutate that data and return the result.
that would, imho, make it unit testable. and when you unit test it, you wouldn't have to mock the db at all, as you could simply write the data you wanted to mutate and supply it the function.
Related
I would like to run the individual tests (functions) of my Python unittest Class in sequential order and not in parallel. I can tell it is parallel because the first function/test writes a record into the TinyDB and another function/test - which fails - needs to read that new record and make an existence test.
So, how do I enforce the strict sequential test execution?
If that is NOT possible, can I enforce the strict sequential processing in creating multiple tests? (I would dislike to do so, because I would like to have a 1:1 relationship of modules and their test_modules.)
Answer for unittest
A strict execution I could realize by creating a master test py file. Named it run_all_tests.py
The modules have separate classes. I trigger them one by one. Respectively the functions.
Switching to pytest and fixtures
Anyhow, I dislike that short-coming of controlling the sequence in a sophisticated/declarative way on a function level. Thus I switched to pytest.
First of all I like that there is an argument that shows the sequence. That confirms what we are expecting:
pytest -setup-show test_myfunction.py
On top of it, you may apply the decorator #pytest.fixture() to a method that is run before. This does NOT necessarily help us with the sequence in first line. Complementary, it reminds us of making independent tests - where one uses the #pytest.fixture() annotated method as an argument to the test function. This way one has a deliberate fixture for a single function. Do NOT mistaken that as the same as the setUp() method of unittest. They run before every single method. Every. And the setUpClass() runs once before any test function is invoked.
For those who still want declarative order, you find it here: https://pypi.org/project/pytest-order/, https://github.com/pytest-dev/pytest-order
I am trying to write some simple code in haskell where there is a function performs a simple database query. In order to unit test Iam using HUnit but not sure how I can mock the database connection and query response.
Pass the function that performs the database query as a parameter to your code, instead of having it "hardwired". During tests, pass a mock function to the code. In production, pass a function that really performs the database query.
This new function parameter should be at the right level of abstraction. For example, something like
queryDbForClient :: Connection -> SQLString -> ClientId -> IO (Maybe RowData)
is possibly a bad idea, because it still forces the code under test to be aware that things like Connections and SQL strings exist. Something like this
findClientById :: ClientId -> IO (Maybe Client)
would likely be better, because then you are free to pass functions that don't use db-specific Connection types at all. They could, for example, be backed by an in-memory reference.
Notice that you can build findClientById out of queryDbForClient by partial application and mapping the result a little. But this should be the task of some setup code, not of the main code that you want to test.
Once you start passing functions in this way for the sake of testability and configurability, some common issues start to appear. For example, what if I have multiple dependencies? Passing them all as positional parameters is a chore. This might lead to passing them together in a record-of-functions, perhaps using Has-like typeclasses so as not to tie your main code to any particular record.
I am looking for the name and info on a pattern (?) that I'm contemplating. As I don't know the name, it's difficult to search for it.
Here's what I'm trying to do, with a totally hypothetical example...
find-flight ( trip-details, 'cheapest') :: flight
I have this public function, find-flight(...), that accepts 2 parameters, trip-details and some instruction to apply. It returns a single flight, not a list of them.
When I call it with 'cheapest', the function will wait for all available flight results to come in from expedia, travelocity, hotwire, etc, to assure the cheapest flight is found.
When I call it with 'shortest-flight', the function would do the same kind of underlying work as 'cheapest' but would return the shortest flight. I'm sure you can come up with other instructions to apply.
BUT! I'm specifically interested in a variant of this: the instruction (implied or not) would be 'I-am-filthy-rich-and-I-want-to-buy-a-ticket-now'. In other words, the function would call all the sources such as expedia, orbitz, etc, but would return the very first internally received result, at any price point.
I'm asking because I want my public function to be as quick as possible. I can think of a number of strategies that would make it respond fast, but I'm not sure that I know which approach would be best considering that the parameter is unknown until called, right?
So I'm thinking about writing various versions of this function that would all be called by the public version. It'd return the first result. Then, the other strategies could optionally be aborted. If I did that, I could get some metrics on the function and further optimize.
If I were to write this in Java, I'd have a bunch of future objects that the function would loop through to see which one is done first. I'd return that one.
What's that called?
It's been proposed that the pattern is called Promise Race
I am new to hypothesis and I am looking for a way to generate a pair of similar recursive objects.
My strategy for a single object is similar to this example in the hypothesis documentation.
I want to test a function which takes a pair of recursive objects A and B and the side effect of this function should be that A==B.
My first approach would be to write a test which gets two independent objects, like:
#given(my_objects(), my_objects())
def test_is_equal(a, b):
my_function(a, b)
assert a == b
But the downside is that hypothesis does not know that there is a dependency between this two objects and so they can be completely different. That is a valid test and I want to test that too.
But I also want to test complex recursive objects which are only slightly different.
And maybe that hypothesis is able to shrink a pair of very different objects where the test fails to a pair of only slightly different objects where the test fails in the same way.
This one is tricky - to be honest I'd start by writing the same test you already have above, and just turn up the max_examples setting a long way. Then I'd probably write some traditional unit tests, because getting specific data distributions out of Hypothesis is explicitly unsupported (i.e. we try to break everything that assumes a particular distribution, using some combination of heuristics and a bit of feedback).
How would I actually generate similar recursive structures though? I'd use a #composite strategy to build them at the same time, and for each element or subtree I'd draw a boolean and if True draw a different element or subtree to use in the second object. Note that this will give you a strategy for a tuple of two objects and you'll need to unpack it inside the test; that's unavoidable if you want them to be related.
Seriously do try just cracking up max_examples on the naive approach first though, running Hypothesis for ~an hour is amazingly effective and I would even expect it to shrink the output fairly well.
I came from JS world and I am used to do thorough testing of all the possible cases that can be a result of weak typing. That way, inside a function I check all the incoming parameters to conform to some criteria.
As an example, in function createUser(username, id, enabled, role){} I would check if username is a string, id is a UUID, status is boolean, and role is a string that must be 'admin', 'user' or 'system'.
I create tests for these cases to make sure that when I pass wrong parameters, tests fail and I need to find bugs that lead to this. At the end, I have quite a lot of tests, many of which are type-checking tests.
Now, I am playing with Swift which is strongly-typed. I use it to create a client app that consumes data from a NodeJS server side. If I want to create a similar createUser() function in Swift, it seems like I need much less tests because type checking is in the language itself.
Is it right to think that a basically a strongly-typed language needs less tests than a weakly-typed one? Some tests just seem to be unnecessary in Swift and the whole test process seems to be more lightweight.
Are there things I can do to write even less tests by using language constructs in some specific manner and still be sure the code is correct and would pass tests by definition?
The use of
optionals and non-optionals, guard, if let
may save you some nil checks
for example -
Guard Statement
A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
A guard statement has the following form:
guard condition else {
statements
}
and more generally, read this -
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html