Git joy

Following are 2 examples when git made my life easier. I realize some of these also apply to other version control systems, but I’m pretty sure they don’t apply to all of them.

Splitting big changes

Sometimes I make too many changes (possibly in the same file) but I want to only keep part of them.

Here’s the example scenario:

  • You start making changes rapidly and experiment with different things
  • The diff becomes huge
  • You want to keep part of the experimental changes and throw away the rest
  • git add –patch
  • git asks you for every hunk (part of the diff) wheter you want to add it or not

Now you can only add parts of the changes to a file and commit them. Then you can do whatever you want with the rest of the changes — commit them to another branch, discard them,
stash them, etc. See also git checkout --patch

Working in parallel

This is one of the huge wins with git (compared to svn/perforce at least). It is extremely simple to work in parallel by creating branches. Here’s an example scenario

  • You want to try N different solutions to the same problem, or just work on N different problems,
    switching between them
  • You create N branches
  • You switch between branches until you finish some or all of them and decide which ones you want to keep
  • At this point you can just merge each of the branches you want to keep in your primary branch (master)

Bug Hunting

You know that a particular commit in your history is “good”, and another one is “bad”. How do you find what causes the “badness”?

You can start by looking at the difference between those two commits:
$ git diff

If from the diff it’s not obvious what broke, you can use a very handy git command
git bisect which assists you in doing a binary search in a cycle similar to this:

You can start the process with:

$ git bisect start
$ git bisect bad
$ git bisect good
Bisecting: 3 revisions left to test after this (roughly 2 steps)

At this point git has checked out the commit that’s half between bad and good.
You can test whether this is a good or bad commit, and tell git about it.

You repeat this process until git victoriously shows you the offending commit.

ADO Resync() and autoincrement with PostgreSQL

I was forced to do a project in classic ASP. Of course, I chose Javascript. And PostgreSQL. I use the unicode ODBC driver for PostgreSQL. I connect with a DSN (you need to create a data source in the windows control panel (yuck) ).

And I actually made a small Object Relational Mapper that kinda works very well for now. It’s about 400 lines of code for now. However, that’s another topic.

When I was implementing the save() method for my models I needed to insert some records
and after that to access their fields.

The solution is to use the AddNew() method of a recordset. So:

                var rs = Server.CreateObject("ADODB.Recordset");
                rs.CursorLocation = 3; // adUseClient, without this, resync() does not work!

                rs.Open(quoted_table_name, db._conn, 3, 3, 512);

                rs.AddNew(cols, vals);
                rs.Resync();
                /* Do stuff with the rs fields, like get a default value that the database put for us */

                rs.Close();

I know it sucks seing integers instead of constant names, but I haven’t gotten around to reference the DLL that defines these constants (or whatever, I read something in an ASP book).

The important line is the second one. 3 is adUseClient, which means “Uses a client-side cursor supplied by a local cursor library” whatever that actually means. That was the key after about an hour spent trying to solve this shit! If you do not set the CursorLocation, you’ll get an error when you call Resync() saying that the current provider does not support refreshing underlying variables.

Unfortunately, this does not work with primary key values like autoincrement IDs, which was my first intent.

However, after many more minutes surfing the internet I have finally found the solution!

Well, this works only when the primary key is an autoincrement value. So we use resync() when the
field is not AI, and the absolutePosition method, otherwise.

My code looks like this now:

// Part of the save() method
                var rs = Server.CreateObject("ADODB.Recordset");
                rs.CursorLocation = 3; // adUseClient. This is required
                rs.Open(quoted_table_name, db._conn, 3, 3, 512);

                rs.AddNew(cols, vals);
                rs.Update();
                this._refresh(rs);

                rs.Close();
        /* Refresh values in the object from a recordset
         * Changes argument rs
         * For internal use only
         *
         * - If the model has a serial (autoincrement, AI) field,
         *   that was specified in the creation of the model,
         *   to refresh the row, we use absolutePosition and Requery().
         *   - If there is column named 'id', we assume it to be AI
         *     and to the same as above.
         *
         * - If klass.serial is null, we do not make the assumption about
         *   the 'ID' column
         * 
         */
        _refresh: function(rs) { 

            if(klass.serial || (this.id === null && klass.serial === undefined)) {
                var pos = rs.absolutePosition;
                rs.Requery();
                rs.absolutePosition = pos;
            }
            else {
                rs.Resync();
            }

            var cols = klass.columns;
            for(var i in cols) {
                 this[cols[i].name] = rs.Fields(cols[i].name).value;
            }

        },

Unit testing in C++ using cxxtest

Yesterday I started to poke around with the cxxtest testing framework.

So basically, to start right off you need:

  • Source file to test. It shouldn’t have a main function. At least if you do things the way I did which is by linking the compiled object file with the test runner object file (which defines a main function).
  • A header file which defines the actual test.
  • A Makefile that defines the rules needed to compile all of this.

Source files to test

So this is the simple source code that I am going to test

#include "parser.hpp"

inline bool Parser::surrounded_by(const string& s, char left, char right)
{
  return s.at(0)==left && s.at(s.length()-1)==right;
}

void Parser::strip(string& s) {
  static const string filter="\r\n\t ";

  size_t right = s.find_last_not_of(filter);
  if(string::npos == right) {
    s.clear();
    return;
  }

  size_t left = s.find_first_not_of(filter);
  if(string::npos == left) left=0;

  s=s.substr(left,(right-left)+1);
}

And this is the header file:

#ifndef PARSER_HPP_
#define PARSER_HPP_

#include <string>
#include <map>

using std::map;
using std::string;

namespace Parser {
  inline bool surrounded_by(const string& s, char left, char right);
  void strip(string& s);
}
#endif

The actual test

I like things neatly tucked into directories so I made a subdir test. There I have a file named parserTest.h with the following content
Note: I don’t know why but WordPress displays the NULL character \ 0 (lines 51 and 54) as a space, so I wrote 0 instead.

#include <cxxtest/TestSuite.h>
#include "parser.hpp"
using std::string;

class ParserTestSuite : public CxxTest::TestSuite {
  public:
  void testStrip()
  {
    string s=" strip me  ";
    Parser::strip(s);
    TS_ASSERT_EQUALS(s,"strip me");
  }
  void testNoStrip()
  {
    string s="don't  strip me", s1=s;
    Parser::strip(s);
    TS_ASSERT_EQUALS(s,s1);
  }
  void testStripLeft()
  {
    string s="  left strip me";
    Parser::strip(s);
    TS_ASSERT_EQUALS(s,"left strip me");
  }
  void testStripRight()
  {
    string s="right strip me  ";
    Parser::strip(s);
    TS_ASSERT_EQUALS(s,"right strip me");
  }

  void testSurrondedBy()
  {
    const string s="?am I surronded by questionmarks?";
    TS_ASSERT( Parser::surrounded_by(s, '?', '?') );
  }
  void testNotSurroundedBy() {
    const string s="I'm the authority";
    TS_ASSERT( !Parser::surrounded_by(s, ' ', ' ') );
  }
  void testLeftOnlySurrondedBy() {
    const string s="?Left yes but right no.";
    TS_ASSERT( !Parser::surrounded_by(s, '?','!') );
  }
  void testRightOnlySurroundedBy() {
    const string s="Left no but right yes!";
    TS_ASSERT( !Parser::surrounded_by(s, '?', '!') );
  }
  void testNotSurroundedByNullChar() {
    const string s="Am I terminated by a null char? Are we all?";
    TS_ASSERT( !Parser::surrounded_by(s, 'A', 0) );
  }
  void testCStringNotSurroundedByNullChar() {
    TS_ASSERT( !Parser::surrounded_by("A C string", 'A', 0) );
  }
  void testCStringSurroundedBy() {
    TS_ASSERT( Parser::surrounded_by("! Yes !", '!', '!') );
  }

};

Of course this blog entry is just an example of how to basically use cxxtest. So you should check out the manual (html | pdf) (as always) to see much more info. Also in the cxxtest source tree there is a directory sample that holds Makefilse for different operating systems and a few basic tests. The main difference between my sample and the ones in the source code tree of cxxtest is that I have subdirectory that holds the tests, hence the Makefiile is a bit different (also, I’ve stripped some of it that I don’t need, like GUI output).

The Makefile

So, the Makefile is really important. Just put it in test/Makefile. Of course, you should edit the paths in the SHELL and TESTGEN directory. The TESTGEN variable holds the path to the Perl script that generates the test runner cpp file (called error_printer here) which is later compiled and run.

SHELL = /bin/bash
VPATH = ..:.
CXXC = g++ -Wall -I. -I..
CC = g++ -c -I. -I..
TESTGEN = /usr/bin/cxxtestgen.pl
TARGETS = error_printer
TESTS = *.h

all: $(TARGETS)
clean:
	rm -f *~ *.o *.obj $(TARGETS) $(GUI_TARGETS)
	rm -f tests.cpp error_printer.cpp
	rm -f qt_runner.cpp

distclean: clean
	rm -f Makefile

run: error_printer
	./error_printer

error_printer.cpp: $(TESTS)
	$(TESTGEN) -o $@ --error-printer $(TESTS)

stdio_printer.cpp: $(TESTS) parserTest
	$(TESTGEN) -o $@ --runner=StdioPrinter $(TESTS)

tests.cpp: $(TESTS)
	$(TESTGEN) -o $@ $(TESTS)

error_printer.o: error_printer.cpp
	$(CC) error_printer.cpp -o error_printer.o

error_printer: error_printer.o parser.o
	$(CXXC) error_printer.o parser.o -o error_printer

%: %.cpp
	$(CXXC) -o $@ $<

Now to run the tests we do
make run
in the test directory.

The output is:

[emil@lappy test]$ make run
/usr/bin/cxxtestgen.pl -o error_printer.cpp --error-printer *.h
g++ -c -I. -I.. error_printer.cpp -o error_printer.o
g++    -c -o parser.o ../parser.cpp
g++ -Wall -I. -I.. error_printer.o parser.o -o error_printer
./error_printer
Running 11 tests.........OK!