77 points · by BerislavLopac · 5y ago · 43 comments
All too often someone puts me in some weird IDE and I feel like a cat with boots on.
I told them flat out no, gave them my ip, made an account on my local machine and started a shared tmux session over ssh. Since that's my usual ide I didn't lose any capability.
But I have to have my ip publicly accessable (permission from isp?) beforehand right?
Are other companies copying them to the Tee?
Write a function biasedcoin(n,p) that takes the number of coin flips, n, and the probability of heads, p. It flips a biased coin n times, and returns the ratio of number of heads/number of tails. p is guaranteed to have two significant numbers eg. p = 0.60 or p = 0.74. You should use the random.randrange function to generate random numbers.
Example implementation
def biasedcoin(n,p):
import randrange from random
heads = tails = 0
for i in range(n):
if randrange(100) < 100*p:
heads += 1
else:
tails += 1
return heads/tailsYour test should not depend on the internal workings of randrange or anything relying on unfixed random state. Your test is only checking if, given correct results from randrange (or any other external world source of random draws) that the rest of your function correctly produces the two-digit bias number.
Otherwise you are just testing randrange itself.
If you are asking how to test a pseudorandom number generator, you have a few choices. You can either fix the random seed and test the algorithm’s precise implementation on a large number of known results. Or you can define tests statistically with margins of error, for example testing the entropy in a series of uniformly generated bits or the resulting distribution in a series of random draws from a fixed list, and decide what level of precision is tolerable before considering a test failed.
"Randrange" isn't hard to get to behave in the way you want. In fact, the way you want it to behave here is all it does!
I'd argue if what you want is to do engineering, mocking this isn't what you'd want to do. You want to ensure your code works. And your test can tell you that it works, even if "randrange" works differently while maintaining the same signature after you update the module it came from.
If you're doing software engineering for aviation for example, I doubt "well, my tests using mocks passed, it's just that the dependency broke it's contract" is a good enough excuse for a catastrophe.
You should have a completely different set of tests (integration tests / end to end tests) that exercises important unmocked validation points. And your test runner should allow you to seamlessly switch between the two sets or combine them.
For example, use @pytest.mark.integration to distinguish all tests needed unmocked dependencies, and have some “integration-tests.ini” config for that.
Then “pytest” runs all the tests with mocks (runs fast, tests logical correctness with tight feedback) and “pytest -c integration-tests.ini” runs all tests or runs the subset requiring real third party resource access. It can run slower, sometimes fail for flaky reasons like network blip, etc.
Thank you for this. Another way to put this is "your tests for code that uses a 3rd party API should not amount to an uptime test for the 3rd party API."
Some time ago, I observed that tests in the Boost.Accumulators library were similarly confounding tests for the code one wrote vs tests of statistical hypotheses:
Why not just pass in 'randrange' as a function argument?
def findBias(randrange):
heads = tails = 0
for i in range(n):
if randrange(100) < 100*p:
heads += 1
else:
tails += 1
return heads/tails
import random
bias = findBias(random.randrange)
def myTest():
result = findBias(lambda: generateInSomeWay)
assert checkInSomeWay(result)
It's amazing to me how many complicated and convoluted hacks people can come up with, to avoid calling a function with an argument.This is how nasty convoluted API get created. Now other functions up the call stack will also have to have a randrange param if they have to pass it forward.
At best I could say in some unique use cases there could be API trade offs that make this ok, but definitely not at all for passing around pseudorandom sampler functions. Your change is strictly more confusing, has strictly worse coupling and has a strictly worse API and even after all that, the test is not simpler and isn’t even less code than a one-liner mocker.patch in pytest.
I am trying to write tests to autograde some HW assignments, and so I really have to think adversarially and imagine my students writing the weirdest yet correctly working functions.
I really haven't come up with a better answer than checking the statistics of the returned value by running the function a whole bunch of times, like you suggest.
def biasedcoin(n, p):
for answer in answer_key[n][p]:
yield answer
Or this: def biasedcoin(n, p):
while True:
mine_bitcoin_on_teachers_computer()You can easily implement a grader that checks the the proof.
Of course that still leaves the generation and randomness part. You could make a separate function for numberToTailOrHead(...) that you can test. Or maybe you should have the ability to send in which source of randomness it uses. And then you can provide a fake random implementation that tests the edge cases (0, 0.5, 0.999).
First, if you can ensure the seed of the generator, then that could be used on a case by case basis. But this tricky, since it introduces a subtle dependency on the implementation of biasedcoin.
Another option is to split the function/process into a stochastic and deterministic part. Test the deterministic part thoroughly. biasedcoin is too trivial for this, but it works nicely in more complicated setups.
For biasedcoin, I would probably go with a statistical approach. Given a certain bias, the expected value and distribution is known. I would simply test that several trials of the function lie within some bound.
For example, if the test flips the coin 1,000 times, there is better than a 99% chance that the outcome would result in 450 to 550 heads. So if you write the test using `450 <= heads <= 550`, you know that it will fail ~1% of the time. And if you expand the range to reduce the rate of false negatives, you have reduced the confidence the test is validating correctness.
Having said that, I still find statistical tests to be very helpful when building out code that uses randomness. However, these tests typically do not make it into the CI/CD pipeline.
(Also, it’s part of the standard library.)
https://github.com/tmoertel/practice/blob/master/dailycoding...
https://github.com/tmoertel/practice/blob/master/dailycoding...
https://github.com/tmoertel/practice/blob/master/dailycoding...
(There’s the option to get that behaviour in pytest as well with a parameter. Also, pytest may run the tests in parallel, which may speed up the results)
if i > 0 and (minimum == 0 or i < minimum):
minimum = iI really wish more was said than just this. Why is it that pytest is often preferred and unittest is considered a bad choice? What is the impact on the quality of the tests?
- lets you use regular assert statements, rather than assertEqual, assertTrue, etc.
- does not impose the use of classes
- the way it does fixtures just feels nicer to use than unittest
Basically, it's more ergonomic and IME more flexible.
You write the test for your non-existent model, then write the model and try to train the model to 'pass' the test? Do you also train it on the test case or on other data only?
Test that this ETL function expects a DataFrame with a given schema and returns one with a different (but also known) schema, even with all these edge cases in the filters and group-bys.
Test that the "train_classifier" method/function rejects negative penalisation parameters, returns an object of type X (a trained sklearn object say, or dictionary of weights that can be deserialised), fails loudly if you don't have enough samples from category Y etc.
Test that the predict method returns a probability as a float, a predicted class as an int, a DataFrame with metadata and headers, etc etc.