<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/how-to-write-good-tests-in-r/"></div></div><div><a data-url="http://www.r-bloggers.com/how-to-write-good-tests-in-r/" data-counturl="http://www.r-bloggers.com/how-to-write-good-tests-in-r/" data-count="horizontal" data-text="How to write good tests in R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://cartesianfaith.com/2016/06/30/how-to-write-good-tests-in-r/"> R – Cartesian Faith</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Testing is an often overlooked yet critical component of any software system. In some ways this is more true of models than traditional software. The reason is that computational systems must function correctly at both the system level and the model level. This article provides some guidelines and tips to increase the certainty around the correctness of your models.</p>
<div class="wp-caption"><img height="234" width="450" src="https://i1.wp.com/www.clevelandmn.govoffice2.com/vertical/Sites/%7B581E59BA-AE7A-481A-81E0-862AA9F2D577%7D/uploads/%7BABD30A6A-EFC4-401F-82E9-721385E04A63%7D.JPG">
<p class="wp-caption-text">Testing is a critical part of any system</p>
</div>
<h3>Guiding Principles</h3>
<p>One of my mantras is that a good tool extends our ability and never gets in our way. I avoid many libraries and applications because the tool gets in my way more than it helps me. I look at tests the same way. If it takes too long to test, then the relative utility of the test is lower than the utility of my time. When that happens I stop writing tests. To ensure tests are worthwhile, I follow a handful of principles when writing tests.</p>
<p>In general, tests should be:</p>
<ul>
<li>self contained – don’t rely on code outside of the test block;</li>
<li>isolated – independent and not commingled with other test cases;</li>
<li>unique – focus on a unique behavior or property of a function that has not been previously tested;</li>
<li>useful – focus on edge cases and inputs where the function may behave erratically or wildly;</li>
<li>scalable – easy to write variations without a lot of ceremony.</li>
</ul>
<p>By following these principles, you can maximize the utility of the tests with minimal effort. </p>
<h3>Testing as Metropolis-Hastings</h3>
<p>I like to think about testing as an application of MCMC. Think about the function you want to test. If written without side effects, then for each input you get an output that you can examine. Covering every single input is typically untenable, so the goal is to optimize this process. That’s where the MCMC concept comes into play, specifically with the <a target="_blank" href="http://www2.geog.ucl.ac.uk/~mdisney/teaching/GEOGG121/diff/understanding_metropholis_hastings.pdf">Metropolis-Hastings algorithm</a> (M-H). This technique produces random samples that follows an arbitrary probability distribution. What this means is that where a distribution is dense, there will be more points versus in an area with low probability.</p>
<p>Now think about testing. Usually we care about edge cases and boundary conditions as this is where a function may behave unexpectedly. We need more tests for these conditions and less tests where we know values are well-behaved. In terms of M-H, given a probability distribution of likely inputs, we want to create test cases according to the inverse of this distribution! Following this approach, it’s actually possible to generate test cases randomly with a high degree of certainty that they cover the most critical inputs of the function.</p>
<h3>Sane Test Creation and Management</h3>
<p>It’s not uncommon for tests to be written at the get-go and then forgotten about. Remember that as code changes or incorrect behavior is found, new tests need to be written or existing tests need to be modified. Possibly worse than having no tests is having a bunch of tests spitting out false positives. This is because humans are prone to habituation and desensitization. It’s easy to become habituated to false positives to the point where we no longer pay attention to them.</p>
<p><img height="219" width="313" src="https://i1.wp.com/www.simplypsychology.org/systematic-desensitisation.jpg"></p>
<p>Temporarily disabling tests may be acceptable in the short term. A more strategic solution is to optimize your test writing. The easier it is to create and modify tests, the more likely they will be correct and continue to provide value. For my testing, I generally write code to automate a lot of wiring to verify results programmatically.</p>
<p>The following example is from one of my interns. Most of our work at <a target="_blank" href="http://pez.ai/">Pez.AI</a> is in natural language processing, so we spend a lot of time constructing mini-models to study different aspects of language. One of our tools splits sentences into smaller phrases based on grammatical markers. The current test looks like</p>
<pre>
df1&lt;-data.frame(forum=&quot;Forums&quot;, 
                title=&quot;My printer is offline, how do I get it back on line?&quot;, 
                thread.id=5618300, 
                timestamp=&quot;2016-05-13 08:50:00&quot;,
                user.id=&quot;Donal_M&quot;,
                text=&quot;My printer is always offline, how do I get it back on line?&quot;,
                text.id=1)

output_wds1&lt;- data.frame(thread.id=c(5618300,5618300,5618300),
                        text.id= unlist(lapply(c(1,1,1), as.integer)),
                        fragment.pos=c('C','C','P'),
                        fragment.type=c('how','it','on'),
                        start=unlist(lapply(c(1,5,7), as.numeric)),
                        end=unlist(lapply(c(4,6,8), as.numeric)),
                        text=c('how do i get','it back','on line'))

output_wds1$fragment.pos&lt;-as.character(output_wds$fragment.pos)
output_wds1$fragment.type&lt;-as.character(output_wds$fragment.type)

test_that(&quot;Test for HP forum&quot;, {
  expect_equivalent(mark_sentence(df1), output_wds1)
  expect_equivalent(mark_sentence(df2), output_wds2)
})
</pre>
<p>The original code actually contains a second test case, which is referenced in the <code>test_that</code> block. There are a number of issues with this construction. The first three principles are violated (can you explain why?) not to mention that it’s difficult to construct new tests easily. Fixing the violated principles is easy, since it just involves rearranging the code. Making the tests easier to write takes a bit more thought.</p>
<pre>
test_that(&quot;Output of mark_sentence is well-formed&quot;, {
  df &lt;- data.frame(forum=&quot;Forums&quot;, 
    title=&quot;My printer is offline, how do I get it back on line?&quot;, 
    thread.id=5618300, 
    timestamp=&quot;2016-05-13 08:50:00&quot;,
    user.id=&quot;Donal_M&quot;,
    text=&quot;My printer is always offline, how do I get it back on line?&quot;,
    text.id=1)

  # act = actual, exp = expected
  act &lt;- mark_sentence(df)

  expect_equal(act$fragment.pos, c('C','C','P'))
  expect_equal(act$fragment.type, c('how','it','on'))
  expect_equal(act$start, c(1,5,7))
  expect_equal(act$end, c(4,6,8))
})
</pre>
<p>Now the test is looking better. That said, it can still be a pain to construct the expected results. An alternative approach is to use a data structure that embodies the test conditions and use that directly. </p>
<pre>
exp &lt;- read.csv(text='
fragment.pos,fragment.type,start,end
C,how,1,4
C,it,5,6
P,on,7,8
', header=TRUE, stringsAsFactors=FALSE)
fold(colnames(exp), function(col) expect_that(exp[,col], act[,col]))
</pre>
<p>(Note that <code>fold</code> is in my package <code><a target="_blank" href="https://cran.r-project.org/web/packages/lambda.tools/index.html">lambda.tools</a></code>.)</p>
<p>The rationale behind this approach is that it can be tedious to construct complex data structures by hand. Instead, you can produce the result by calling the function to test directly, and then copy it back into the test case. The caveat is that doing this blindly doesn’t test anything, so you need to review the results before “blessing” them.</p>
<p>It’s easy to see how such a structure can easily extend to providing an input file and an expected output file, so even more scenarios can be run in a single shot.</p>
<h3>Conclusion</h3>
<p>For tests to work, we must remain sensitized to them. They need to cause us a bit of anxiety and motivate us to correct them. To maintain their effectiveness, it’s important that tests are easy to create, maintain, and produce correct results. Following the principles above will help you optimize the utility of your tests.</p>
<p><em>This site generously supported by <a target="_blank" href="https://www.datacamp.com/">Datacamp</a>. Datacamp offers a <a target="_blank" href="https://www.datacamp.com/courses/free-introduction-to-r">free interactive introduction to R</a> coding tutorial as an additional resource. Already over 100,000 people took this free tutorial to sharpen their R coding skills.</em></p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/cartesianfaith.wordpress.com/2151/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/cartesianfaith.wordpress.com/2151/" border="0"></a> <img alt="" src="http://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/how-to-write-good-tests-in-r/"></div></div><div><a data-url="http://www.r-bloggers.com/how-to-write-good-tests-in-r/" data-counturl="http://www.r-bloggers.com/how-to-write-good-tests-in-r/" data-count="vertical" data-text="How to write good tests in R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://cartesianfaith.com/2016/06/30/how-to-write-good-tests-in-r/"> R – Cartesian Faith</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/io_xmlnotUE"></a></div>