SecureRandom gotcha

If you need a random number you are usually advised to use SecureRandom because it gives a cryptographically secure random number.

Typical way of calling SecureRandom would be:

From a random generator seeding perspective this is also the correct way. You might be tempted to call the setSeed in order to seed with some long that you provide. Resist that temptation unless you can prove that the seed obeys the constraints of your application (like that it is different between different instantiations and invocations of SecureRandom). And no, seeding with the System.currentTimeMillis() will not work: multiple threads can get the same value.

Here’s an excerpt from the setSeed documentation:

The interesting part here is that it says that the seed “supplements” the internal seed. This is not what I found. The given seed will completely replace the internal seed. This means that when seeded the same way two SecureRandom will return the same value. Probably not what you would expect.

 

Emacs is awesome!

Here’s an elisp function that will just underline your current text. It’s simple, awesome and I use it all the time for my titles. You can put it in the *scratch* and do a C-x C-e and then call it with M-x add-underlining.

 

JUnit Argument Captor — enhance your mock testing

When writing mock tests it is, sometimes, more convenient to assert the values with which the methods were called using the ArgumentCaptor
class instead of the more usual mock verify.
Let’s see both in action.

We’ll take as sample a mock of the List interface.

Let’s see how verify-ing would work:

Or since we expect those to be called in that same exact order we could also:

Now let’s use ArgumentCaptor instead:

That seems more streamlined and readable IMO. As you can see the ArgumentCaptor will catch all arguments with which it was called.

If you expect a single value to be captured or if you’re only interested in the last value with which your method was called you can also call:

In our case that call will return “three”.

JUnit Categories

Hey there, this is my second post on JUnit and its lesser known features. To read the first one go here.

JUnit Categories allow tagging tests thus dividing the tests into separate buckets. This, in turn, becomes important in order to choose which tests run at a later time.

I find categories in combination with maven quite useful in splitting tests into unitary and integration tests. This is probably better understood with an example.

 

Following maven config will split the tests into unitary tests and integration tests. Note how we’re using surefire for the unitary tests and failsafe for the integration tests. We could have used surefire all the way and by all means do if you only have unitary tests. However, failsafe makes sure that failing tests are torn down correctly and that the post-integration-test phase (that comes after the integration-test) is called. The surefire plugin would just stop everything during the integration-test phase. But, anyways, this is maybe an article for another time. Here’s the example:

 

In order to skip the integration tests you can add -DskipITs command line parameter to the maven invocation.

JUnit Rules

We all know testing is good for our health right? “Testing rocks, debugging sucks”, I think the good guys at google said it.

When in Java when writing unitary tests, we use JUnit most of the time. JUnit is a *wealth* of features which are mostly unexplored and that can truly make test writing easier and more enjoyable.

I’m planning to write a series on the hidden or the lesser known JUnit.

And the first one today is: Rules.

What Rules allow is, in a word, to run code that wraps the test code under execution. In many cases that’s just code that
initializes and destroys some helper objects that you need in the testing code. So why wouldn’t you put that in methods annotated with @Before/@After? The answer is convenience.

An example is worth 1000 words. Let’s see how @Rule TemporaryFolder is used.

What’s nice about the @Rule in the example above is how the TemporaryFolder functionality is encapsulated, brought up and torn down for each test.

Rules classes like the TemporaryFolder that we just saw need to inherit interface TestRule which only contains the method below:

In the above, the base parameter represents the actual test code. Calling base.evaluate() will trigger the test.

However implementing the TestRule directly is awkward. A more useful class is ExternalResource (which TemporaryFolder also inherits and specializes for temporary files). This allows using in the test code a resource which is initialized/destroyed. As example, say we wanted to use in our test an http client.

And to use this rule in an actual test:

There are a bunch of other @Rule that ship with JUnit which be tremendously useful:

  • TemporaryFolder – as described above, makes dealing with temporary files pretty painless
  • ExternalResource – generalizes resource set up and tear down
  • ErrorCollector – allows test to continue even after the first problem occurs; the purpose here is to collect all problems in one go
  • Verifier – do checks *after* the test has run and was successful
  • TestWatcher – offers hooks into tests passing or failing; can, for instance, be used in order to make a log of tests that passed/failed
  • TestName – makes possible to have the current test name accessible inside the test itself
  • TimeoutRule – enforce a timeout for the whole test execution
  • ExpectedException – allows specifying exceptions that are allowed to be thrown from the test body. This can also be implemented using the “expect” parameter of the @Test annotation, but I find the ExpectedException easier to use than writing an annotation array
  • ClassRule – applies the same lifecycle as the standard @Rule, but this time to the whole fixture
  • RuleChain – used to order rules

I hope this was a good introduction to rules and that you will put them to good use in your tests.

My Swift strings cheatsheet

The Swift strings support representing Unicode strings natively. As such it is no longer possible to have random access inside the string because some characters might be represented on more than one byte.

I always forget how to do basic things so I put together a cheatsheet that might be useful to others too.

Counting characters

Lowercasing/uppercasing

 

Iterating through the string characters

 

Indexes inside the string

 

Is string contained in another string

 

Split a string by separator, iteratively

 

 

Split a string by separator, recursively

 

Fix UITabBar icon images as alpha-channel

Apple asks that your UITabBar icons be pure alpha-channel images with added anti-alias. That means that usual RGB channel images will just show as a blue square.

So how to go from a normal RGB channel image to a pure alpha-channel. I use Photoshop and there is probably¬†more than one way, but what works best for me is creating a “Gradient map” adjustment layer.

To create a gradient map adjustment layer go to the “Layers” tab and click “Create fill or adjustment layer…” like below.

Screen Shot 2016-01-31 at 18.50.15

Afterwards save your image and all should be fine.

Fix putty garbled text after window resize

So you resized your putty window. When going through history, if there are lines which are longer than 80 chars, the default putty window, then just going through the will show the text garbled.

The fix is simple: tell the terminal the new window size. Arguably this should be automatically done by putty, but hey, there’s a workaround. Checkout the stty command.

Pass the cols parameter to specify the new width of the window in columns.

Find your home directory in the iPhone simulator

This is huge.

Start your application, then “Debug/Pause” it.

Then type this magic into your lldb console (the debugging pane should be at the bottom of the Xcode window).

Your debugger console should now show the local directory where your application has its home.