Unit tests with mockups in LispPosted by Holger Schauer in
Lisp
One of the bigger practical problems with unit testing is isolating the test coverage. Say, you want to test a piece of code from the middle (business) layer. Let's assume further the piece of code under consideration makes some calls to lower level code to retrieve some data. The problem of test coverage isolation is now that if you "simply" call your function, you are implicitly also testing the lower level code, which you shouldn't: if that lower level code gets modified in an incorrect way, you would suddenly see your middle level code fail although there was no change made to it. Let's explore ways to avoid the problems in Common Lisp.
There is a very good reason why you would also want to have such test dependencies to ensure your middle level code still works if the lower level code is extended or modified. But that is no longer unit testing: you are then doing so-called integration tests which are related, but still different beasts. Now, I was facing exactly the typical dreaded situation: I extended an application right above the database access layer which had not seen much tests yet. And of course, I didn't want to go the long way (which I will eventually have to go anyway) and set up a test database with test data, write setup and tear-down code for the db etc. The typical suggestion (for the xUnit crowd) is to use mock objects which brings us finally on topic. I was wondering if there are any frameworks for testing with mock objects in Lisp, but a quick search didn't turn up any results (please correct me if I've missed something). After giving the issue a little thought, it seemed quite clear why there aren't any: probably because it's easy enough to use home-grown solutions such as mine. I'll use xlunit as the test framework, but that's not relevant. Let's look at some sample code we'll want to test:
The issue is with retrieve-data-by-id which is our interface to the lower level database access.And note that we'll use some special functions on the results, too, even if they made just be accessors. Let's assume the following test code:
Now the trouble is: what kind of testdata you'll need to hide between that call to make-test-data depends on the database that's going to get called by compare-data. So what we'll do now is to use mock objects and mock functions. Let's define a mock-object mock-data and a mock-retrieve-data function, which will simply return a single default mock object.
Why that mock-retrieve-data returns a closure will become clear in a second, after we've answered the question how these entirely different named object and function can be of any help. The answer lies in CLs facility to assign different values (or better said) definitions to variables (or better said to function slots of symbols). What we'll do is to simply assign the function definition we've just created as the function to use when retrieve-data is going to be called. This happens in the setup code of the test case:
You can now see why mock-retrieve-data returns a closure: by this way, we can hand the data we establish for the test case down to the mock function without resorting to global variables. Now, the accessor fdefinition comes in extremely handy here: we use it to assign a different function definition to the symbol retrieve-data which will then be called during the unit-test of compare-data.
There is also symbol-function which could be applied similarly and which might be used to tackle macros and special operators. However, the nice picture isn't as complete as one would like it: methods aren't covered, for instance. And it probably also won't work if the function to mock is used inside a macro. There are probably many more edge cases not covered by the simple approach outlined above. Perhaps lispers smarter than me have found easy solutions for these, too, in which case I would like to learn more about them. The release warpPosted by Holger Schauer in
Programming
The Release Warp Lyrics
It's astounding, time is fleeting Madness takes its toll But listen closely, not for very much longer I've got to keep control I remember doing the Release Warp Drinking those moments when The blackness would hit me and the void would be calling Let's do the release warp again... Let's do the release warp again! It's just a bug to the left And then an error to the right With your hands on your keys You bring your fixes in tight But it's the pelvic thrust that really drives you insane, Let's do the Release Warp again! It's so dreamy, oh fantasy free me So you can't find me, no not at all In another dimension, with capitalistic intention Well-secluded, I see all With a bit of a mind flip You're there in the bug slip And nothing can ever be the same You're spaced out on sensation, like you're under sedation Let's do the Release Warp again! Well I was typing down the plan just a-having a think When a snake of a marketeer gave me an evil wink He shook me up, he took me by surprise He had a business plan and the devil's eyes. He stared at me and I felt a change Time meant nothing, never would again Let's do the Release Warp again! (... with sincere apologies to The Rocky Horror Picture Show by Richard O'Brien) UCW leadership changePosted by Holger Schauer in
Lisp
In case you're interested in continuation-based web development with Common Lisp, it might be of interest to learn that Drew Campsie has voluntered to take over UCW development. Marco Baringer, initiator and maintainer of UncommonWeb (aka UCW) seemed somwhat relieved that finally somebody with more time on his hand steps up to take over.
That Marco hadn't had the time to keep pushing UCW is quite obvious from the mailing list archive. Lately Attila Lendvai seemed to me (an innocent external observer) to had pushed UCW foreward, however, as he Attila announced, he wants to go into a different direction than Drew. I've been using ucw-dev during the last two years and the current situation really called for a change, in my opinion. UCWs main problem, as I observe it, is lacking documentation and clearly stated goals which way UCW will go. The automatically extracted documentation doesn't contain information how the bits fit together and all tutorials are a) incomplete, b) outdated as far as they are targetting ucw-dev, whereas development has mainly happened in ucw-ajax. However, it was not all clear that ucw-ajax really would become the main line of UCW. I like UCWs component architecture a lot and will eagerly follow what is going to happen. With two prominent developers such as Marco and Attila more or less leaving the project, it will be interesting to see with how much activity development will happen from now on. Escaping from sql-reader-syntax in CL-SQLPosted by Holger Schauer in
Lisp
This post is mainly a reference post about a particular topic whose solution wasn't immediately obvious to me from the docs to CL-SQL. Using CL-SQL with (enable-sql-reader-syntax), I had written a routine that looks basically likes this:
This is ugly because the only difference between those two select statements is the check for the criteria, but I had no idea how to combine the two select statements into one, because it's not possible to embed lisp code (apart from symbols) into an sql-expression (i.e. the type of arguments for :where or :order etc.). With the next requirement things would become far worse: The order-by statement needs to get more flexible so that it is possible to sort results by year first. Given the approach shown above this would result in at least four select statements, which is horrible. So, naturally I wanted a single select statement with programmatically obtained :where and :order-by sql expressions. Step 1: It occured to me that it should be possible to have the arguments in a variable and simply refer to the variable. E.g., using a more simple example:
So I could now have my two different where-args and two different order-args and use a single select statement. Main problem solved. Step 2: But for the :where arg in my original problem, only a small fraction of the sql-expression differs. So how do I avoid hard coding the entire value of where-arg? How can I combine some variable part of an sql-expression with some fixed parts? I.e, ultimately I want something like:
But with CL-SQL modifying the reader, there seems to be no way to make <put comp-op here> work. I didn't knew how to get the usual variable evaluation into the sql-expression, or how to escape from CL-SQL's sql-reader-syntax to normal lisp evaluation. Somewhere in the back of my head where was that itch that CL-SQL might offer some low-level access to sql expressions. And indeed it does. There are two useful functions, sql-expression and sql-operation. sql-operation "returns an SQL expression constructed from the supplied SQL operator or function operator and its arguments args" (from the cl-sql docs), and we can supply the operator and its arguments from lisp -- which is exactly what I want. Now, the nice thing is that it's easy to mix partly handcrafted sql expressions with CL-SQL special sql syntax constructs that will be automatically handled by the reader (if you enable it only via enable-sql-reader-syntax, of course). I.e., for <put comp-op here> we can use sql-operation, but the rest stays essentially the same:
Now, coming back to my original problem, based on this approach I can split out the common part of the :where and :order arguments and combine those with the varying parts as needed and hand them down to a single select statement. Problem solved. Interactive development gets more popularPosted by Holger Schauer in
Programming
It's interesting to see that more and more environments for interactive development are popping up. If you're wondering what I'm refering to, it's what has traditionally been labelled as an interpreter: you get some kind of prompt like in a command shell and can directly enter and run program constructs. In Ruby, irb is the tool to use, whereas most, if not all, Common Lisp systems provide you a REPL whenever you start-up the system. REPL is an abbreviation for read-eval-print-loop and this pretty much sums up how interactive development works: you enter some code into the system, and as soon as you hit enter (i.e. finish up the particular line of code), the system will read and evaluate it ("interpret" it, although CL systems may also compile it automatically), presenting you with the results.
To me, this seems like more people come to understand that the classic edit-compile-debug cycle of traditional compiled languages like C isn't particular well-suited to a bottum-up programming style, as advocated by the agile programming hype. Where is the beef? I've been told that the reason why the asian folk don't use forks and knives when dining stems from the opinion that when dining one merely wants to eat, while all handcrafting (like slicing the meat) belongs to the a-priori cooking. The edit-compile-debug cycle tends to produce code more akin to the western steak style, while interactive development tends to produce smaller code parts, all well prepared (read: tested) from the beginning, so you don't end up with bloody interiors as easily. That's because of two reasons, I think: In an interactive environment testing a piece of code is cheap and easy. Hack up a small routine and enter it. Next step: call the routine with some sample data. No need to compile. In case there's an error, you'll be thrown into the debugger right away. With the traditional edit-compile-debug cycle, you're gonna edit the code, save it, call the compiler, edit another piece of code testing it, compile that, too, run that and only then you'll see if it succeeds. This might scare developers from running such tests to often and in result to produce larger routines/code blocks. Second reason: in the interactive environment you'll typically have somewhat less comfort then in a full-blown editor. So I'm arguing that the slight discomfort will help you in keeping things small because then you'll not gonna need far reaching edit support. There is, however, a price to pay: For starters, because your interactive system provides you with a single environment during development, it's easy to mess it up. That's different with the traditional edit-compile-debug cycle where every time you compile you run the code in a clean environment. This means, old code refering to refactored functions will result in (usually: compilation) errors whereas in interactive development you may miss some spot in need for modification because the old refactored code is still around. Second, when fiddling with some functions, it may happen that one hacks up several variants, maybe with only slightly differing names or argument lists, so it may happen you forget some crucial code when finally saving your carefully crafted solution (where saving here typically means copy it over to some editor, not saving an image as you may do in Smalltalk or Lisp). Another thing is that one has to be careful not to confuse bottum-up interactive development with hacking without thinking or design-less programming. This threat is all to common because with an interactive environment it's just so easy to get started. Unfortunately, without thinking you'll soon end up with problems one and two and even worse, it's likely that after a little while nobody (including you, the author) will be able to maintain the resulting code. But if you're aware of the potential pitfalls, interactive development is a nice way to do explorative programming which avoids a lot of time consuming labour you have to do with the traditional edit-compile-debug cycle. As a side-note, environments offering incremental compilation like Eclipse aim at a similar goal, but only go half the way as they only take care of the edit-compile part. Only when one combines that with a test-driven development style you arrive at a similar point, because now the test code, when automatically run, will take care of immediately running the code in question (the eval/print part as far as testing the code is concerned). To finally come to the reason for this blog post, I was pleased to learn about the Perl Console, which is not the same as the Perl debugger. I'm eager to try it out, although I'm sure that interactive development with a repl and the executable brain dump that Perl code usually is, is a highly dangerous mix. Update: There is also a series of articles about implementing a REPL in Perl which may be of interest. Twentieth century boysPosted by Holger Schauer in
Lisp
This is just a minor rambling inspired by a recent thread on cll about the ups and downs of using Rails. What I find really overwhelming is the lack of proofs that other (typically Lisp-based) frameworks really have so much benefit over the established more traditional frameworks (e.g. Rails, Zope, plain PHP, ...). All I can see is starter documents, tutorials etc. that show how to program yet another blog or reddit clone in some particular framework. I miss fair comparisons and detailed discussions why and where exactly that one particular way of doing things has benefits. And especially with regard to those reddit clone prototypes: AFAICT, reddit was far beyond implementing some half-baked prototype (in Lisp) when they decided to switch (to Python). Yes, for demo purposes reinventing the wheel with some unround edges might be acceptable, but in reality only rolling wheels will be sold and this is where the challenge is.
I believe that while it's nice that frameworks help with implementing your 500 line application, they really need to show their value with large applications. Where is a discussion of a large on-line shopping system in, say, UCW and CL-SQL, with secure shopping over SSL, login handling, input validation, distribution over multiple servers etc.? Now, I'm not suggesting that UCW, Weblocks etc. can't be used to build such websites, but it would be nice to see a much more in-depth explanation/discussion/comparison of how to do it. That would also help increase the credibility of Lisp or at least, of lispers discussing (other) web frameworks. CLOS Video in German/auf DeutschPosted by Holger Schauer in
German, Lisp
In case you're interested in object-oriented programming in Lisp and happen to speak German, you'll be happy to learn that Pascal Costanza of ContextL and AspectL fame (apart of his postings to cll), has given a talk about CLOS, the Common Lisp Object System at the Hasso-Plattner Institut, Potsdam. And while we're at it, Pascal also has a very interesting blog post about the origins of the advice facility.
German: Falls Dich, lieber Leser, interessiert, wie man objekt-orientiert in Lisp programmiert, solltest Du Dich darüber freuen, dass Pascal Costanza, bekannt durch ContextL und AspectL (abgesehen von seinen Postings in cll), einen Vortrag in Deutsch über CLOS, dem Common Lisp Object System, am Hasso Plattner Institut in Potsdam gehalten hat. Und weil wir gerade dabei sind, Pascal hat außerdem einen sehr interessanten Blogeintrag über die Geschichte von 'advice'. Swing the heartache: Interactive DB maintenance in LispPosted by Holger Schauer in
Lisp
Every now and then, I'm still blown away by the elegant power that the repl (read-eval-print-loop) of Common Lisp provides for everyday tasks. A recent example: I needed to fix a broken column definition in one of my Postgres databases. I'm not a DB pro, so I will just drop the column. But of course, we want to retain the old data, so here we go (using CL-SQL):
That's it. First we open a connection, store away the olddata (which will be returned as a list of tuples) in a global variable, modify the table and finally restore the data. Now, what I find really nice about this is that I can operate on the data as if I had an intersection of psql, shell and a real programming language, which is pretty much the point of this blog post. I think that Ruby probably provides a similar environment with irb. And, hey, today I learned that XEmacs comes with an interface to postgres, so I might have been able to do it from within my favourite editor, too ... Lisp golfPosted by Holger Schauer in
Lisp
Some time ago, I was looking at splitting some text with Elisp, Perl, Ruby and Common Lisp. Yesterday, when I again had to do quite the same thing, it occurred to me that the Common Lisp solution was unnecessary complex/long. I'm not a Perl guru, but I believe the following is probably hard to beat even with Perl:
For the uninitiated, it's not the cl-ppcre library which is interesting here but the built-in iteration facilities of format. See the Hyperspec on the control-flow features of format for details. Now, I usually tend to avoid the mini languages that come with Common Lisp like the one of format or loop when writing real programs, but when using Lisp as a glorified shell they come in very handy. Automated unit testing via ASDF?Posted by Holger Schauer in
Lisp
Dear Lazyweb, I'm looking for a way to automate unit testing with the help of ASDF. I'm using XLUNIT at the moment, but this isn't really relevant. What I want to achieve is that on every compilation of some source file, it's corresponding test file will be loaded (and hence the tests it contains run). However, what I seek to avoid is simply adding the test files to the component definition; the test files should be kept separately. From what I gather from the ASDF documentation, this should be possible using :perform forms, but the very same docs leave me wondering how. What I found (looking at Jörg Höhles asdf file for iterate) is how to load and run a complete test-system, but this is not what I want to do. Ideally, I would like to have a single perform instruction looking something like this:
Here #'glorified-find-component needs to recursively follow the components parent and #'find-component-test should return a component c-test (with c expanded, obviously). Now, I guess I'm just clumsily reinventing the wheel and hence I'm wondering if somebody has already solved "the problem".While I'm at it (it referring to testing), Stefil looks like a very interesting test environment in case you're developing your programs with Emacs and Slime. From there, I found a link to Phil Gregory's test framework comparison which I found much more enlightening than the ALUs list of test frameworks. Now I'm all over the shop ... or Converting from RCS to MercurialPosted by Holger Schauer in
Programming
Like I mentioned in a previous post (here), I hadn't looked closer at those modern distributed revision control systems like Git, Darcs or Mercurial. This was mainly due to two facts: As I'm currently neither involved in any major open source project which uses these systems nor in a project at work which requires the facilities offered by such systems, and as there was no easy access for them in XEmacs, the more traditional systems like Subversion, CVS and RCS are fine for me. However, there was this nag that I might miss something and as revision systems always have been somewhat of a pet peeve of mine, I eventually spend some time reading up more on them. I've read quite a lot of discussions on the web, and gathered that mercurial might be worth a closer look, as it claims to be quite easy to handle, comparably well documented and quite fast. And then finally I've read on xemacs-beta that the new vc package (in Pre-Release) would support mercurial as well.
Well, that's where I am now: I have several pieces of code lying around which I sometimes develop on my main machine and sometimes on my laptop when moving around. This is the scenario where a server-based approach to revision control is not what you want: you won't be able to access your server while you're on the road and hence you can't commit. Now, with RCS that's not a problem, as there is no server involved. But of course, since RCS is a file-system local revision system, syncing is a major problem and you have to go to great pains to ensure you don't overwrite changes you made locally in between syncs. I hope that a distributed version control system like mercurial will solve the problem, as I no longer have to decide which version is the current head version, instead cherry-picking change sets at will. But of course, for this to happen, I have to convert my RCS repositories to Mercurial. This doesn't seem to be a common problem: there are a lot of tools for conversion from CVS or Subversion (see Mercurial Wiki, e.g. Tailor for instance), but not from RCS. I ended up following the instructions given in the TWiki Mercurial Contribution page. I have some minor corrections, though, so here we go: -1. (Step 6 in TWiki docs) Ensure all your files are checked in RCS. I won't copy the advice from the TWiki page here, because I believe in meaningful commit messages and would urge you to do a manual check. 0. You'll need cvs20hg and rcsparse which you will find here. You'll need to have Python development libraries installed, i.e. Python.h. For Debian systems, this is in package python-dev. Installation is as simple as two "./setup install" as root which will install the relevant libraries and Python scripts. 1. Create a new directory for your new mercurial repository (named REPO-HG, replace that name):
2. Initialize the repository:
3. (Step 4 in the TWiki document) Create a new copy of your old RCS repository (named REPO here, replace that with the name containing your old RCS files), add a CVSROOT and a config file (mistake one in the TWiki docs: As with all CVS data, the "config" file needs to go to CVSROOT, not to CVSROOT/..). Of course, if you're no longer interested in your old data, you may omit the initial copy.
4. Inside your directory with the old RCS data, move everything out of the RCS subdirectories (mistake two in the TWiki docs: the double-quotes need to go before the asterix):
5. Run cvs20hg to copy your old repository to mercurial. If you don't follow the directory scheme shown below, you'll end up with your new mercurial repository missing the initial letter of the name of all top-level files and directories.
6. Check that everything looks like you would expect: Programming languages I knowPosted by Holger Schauer in
Programming
Joey seems to have inspired a "list of programming languages you know"-contest over on planet.debian.org, so this is mine:
Missing in this list is stuff like Scheme, Dylan, Oz, Oberon, Eiffel, Haskell and probably some other "tiny" languages which I looked at at some point in time and really didn't ever took a second look. Of those, I may take another look at Haskell in the future, but currently I have no concrete plans in doing so. How much playing time does your MP3 collection have?Posted by Holger Schauer in
Linux, Programming
I love the Unix toolbox:
[elendil->Get_the_gore]mp3info -p "%S\t%m:%02s\t%t\n" * | perl -ne '{ $time=$time+$1 if (/^(\d+)[ \t]+(.*)$/); print $2."\n"; } END { print "Total seconds: $time\n"; $min=$time/60; $secs=$time%60; print(sprintf("Total time: %d:%d\n",$min,$secs)); }' 2:10 Fox in a box 3:16 Loaded heart 2:53 All grown up 3:07 Pleasure unit 2:51 Where evil grows 3:16 Casino 2:38 Don't cry 2:24 Mary Ann 3:48 You lied to me before 1:50 So sophisticated 2:50 Little baby 2:44 Sweet potato 2:56 Voodoo doll 1:51 Hammer stomp Total seconds: 2314 Total time: 38:34 Printing out the track number and the track title works only if the file contains an ID3 tag, of course. Splitting the dark side ...Posted by Holger Schauer in
Programming
For a review, I needed to get the track list of a given CD. As the track list wasn't available via CDDB, I went to some large online store and found the tracklist. I need to convert it to XML, though. The original data I fetched looks like so:
1. Fox In A Box 2. Loaded Heart 3. All Grown Up 4. Pleasure Unit ... whereas I need: <li id="1">Fox In A Box</li> <li id="2">Loaded Heart</li> <li id="3">All Grown Up</li> ... After cutting the original data to my Emacs, writing out a simple file and using Perl for that simple transformation seemed just gross. In the past, I've been an Emacs hacker. But no more, or so it seems, since it took me nearly half an hour just to come up with this simple function:
What took the most time was that I've had forgotten to escape the grouping parenthesis in the regular expression and that it took me a little while to accept that there is really no \d or equivalent character class in Emacs regexps. Which probably means that I've been doing too much in Perl, sed and the like. OTOH, it just may hint at the horror of regular expressions handling in Emacs. What I also dislike is that whenever you want some result in Emacs and see it, too, you have to invoke an interactive operation like message. Of course, there is IELM, but this doesn't really help you for interactive functions operating on regions.And five minutes later, I realize I need to convert some string like "The (International) Noise Conspiracy|The Hi-Fives|Elastica" into a similar list structure. With a simple cut & paste and roughly 30 seconds later, I have
Hmm. Perhaps I've come quite a long way on the dark side already ... On the other hand, in Ruby, this is just as simple (I'm using irb, the interactive ruby shell here):
The difference here is the implicit array Ruby generates, which of course in Perl you could hide in the array position of the foreach loop. Note the annyoing misfeature of irb to always show the prompt even when your still continuing your current input line. In Common Lisp we can do it just as short:
The same thing here: The result of the split could have been easily embedded in the loop. The lesson, of course, is that in the end this example only serves to show that things that are easy to achieve in a high-level are indeed easy to achieve. Or to put it otherwise that the use of regular expressions is no more a discriminating feature between programming languages. Here's your XSLPosted by Holger Schauer in
Programming
Gary King discusses some issues of XSLT. He concludes:
I still feel as if there is less here than meets the eye; that it ought to be possible to express these graph-transformations more elegantly and with less fuss and bother. To me, the only interesting part of XSLT isn't XSLT itself, it's the embedded XPath where XSLT's power comes from. XPath is a pair of scissors for cutting out the nodes of an XML document instance you're interested in and is about as powerful (and hence horrible to get right) as regular expressions (although it's something completely different, of course). XSLT is just the framework which provides a relatively boring set of instructions and control-flow operations. And it's "clean functional" design only gets in the way every so often. Sure, coming from a Prolog and Lisp background, I know all the tricks to work around the hassle, but quite often it would be way easier to just set that damned variable *again*. If I want to do clean functional programming, I know where I can find a language without that XML syntax, thanks. Give me the unclean intermix of programming styles offered by Common Lisp anyday, please. Being a Lisp guy just like Gary, I would be happy to use a language with parenthesis, as I have to do XML transformations quite often and the intermix of elements from different namespaces (XSLT namespace and target namespace) is mostly a pain to read and write. Using xslide, an Emacs mode for XSLT, eases the pain a considerable bit, but it still isn't really fun. And sometimes I need to hack XSLT in a proprietary system which only provides editor capabilities that know nothing about XML (think notepad-style editing capabilities) and then XSLT suddenly has the next most horrible syntax imaginable. However, the corporate world has its own rules and to be fair, the major benefit of XSLT is that you have one standard syntax for XML transformations rather than having xyz numbers of incompatible library APIs. Update: Also in response to Gary, David Lichteblau pointed out his approach to (macro-)pre-processing XSLT stylesheets to overcome some of Gary's problems.
(Page 1 of 3, totaling 33 entries)
» next page
|
QuicksearchBlog AdministrationKategorienTagsCalendar
Powered by |
|||||||||||||||||||||||||||||||||||||||||||||||||
Dieser Blog wird von Weblog-Writer.net zur Verfügung gestellt; einem kostenlosen Dienst der IDEE GmbH
Powered by Serendipity 1.3.1.
Design by Carl Galloway.


