Friday, April 29, 2011

Using googletest and googlemock in Eclipse

Since my answer on Stack Overflow doesn't seem to be getting any attention (and thereby helping no-one), I figured I'd post it here. :)

Here's the summary for people already familiar with Eclipse:
  1. Created a new C++ project in Eclipse (I chose Executable > Empty Project)
  2. Downloaded googletest 1.5.0, untarred, and ran ./scripts/ . /contrib
  3. Back in Eclipse, excluded the contrib directory from the Release build configuration, and added /contrib to the include directories (odd, I know)
  4. Added a src directory and added a class named Foo (see below for the contents of Foo.h--I left Foo.cpp empty for now)
  5. Added a test directory in Eclipse, excluded it from the Release build configuration, added /contrib to the include directories, and added new source files FooTest.cpp and AllTests.cpp (see below for contents)
  6. Built and ran the project

#ifndef FOO_H_
#define FOO_H_
class Foo {
virtual ~Foo();
bool foo(void) { return true; }
#endif /* FOO_H_ */

#include "gtest/gtest.h"
#include "Foo.h"
namespace {
class FooTest : public ::testing::Test {
Foo foo;
TEST_F(FooTest, Foo) {

#include "gtest/gtest.h"
#include "FooTest.cpp"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();

Here are the detailed steps:
  1. In Eclipse, open the File menu and select New > C++ Project
  2. Project Type: Executable > Empty Project
  3. Toolchain: Linux GCC
  4. Click Finish
  5. Open a terminal and cd /tmp
  6. wget
  7. cd gtest-1.5.0/
  8. ./scripts/ . /contrib
  9. Back in Eclipse, right-click on the project folder in the Project Explorer pane, then select Refresh
  10. In the Project Explorer pane, right-click on the contrib folder, select **Exclude from build...*, untick only the Release box, and click OK
  11. Right-click on the contrib folder and select Properties > C/C++ Build > Settings > Tool Settings tab > GCC C++ Compiler > Directories
  12. Click on the Add... button, then the Workspace... button, then select /contrib and click OK to add the directory
  13. Click OK once more to accept your changes to the build settings
  14. Right-click on the project in the Project Explorer pane and select New > Folder, enter src as its name, and click OK
  15. Right-click on the src folder in the Project Explorer pane and select New > Class, name it Foo, then click OK (see above for contents of Foo.h; Foo.cpp can be left as is)
  16. Right-click on the project in the Project Explorer pane and select New > Folder, enter test as its name, and click OK
  17. Follow the steps above to add /contrib and /src as include directories to the test directory
  18. Right-click on the test folder, then select New > Source File to add AllTests.cpp to the test folder, then repeat the same steps to add FooTest.cpp (see above for contents)
  19. Right-click on FooTest.cpp and select Exclude from build..., click the Select All button, then OK
  20. Right-click on the project in the Project Explorer pane, and select Properties > C/C++ Build > Settings > Tool Settings tab > GCC C++ Linker > Libraries, then click the Add... button, enter pthread (required by googletest), click OK to add the library, then OK once more to accept the changes
  21. Hit Ctrl-b to build the project
  22. Hit Ctrl-F11 to run the project
  23. Victory!

Monday, April 11, 2011

nagios-mode for Emacs

Thanks for nagios-mode.el, Michael Orlitzky! Here's how I achieved syntax highlighting-induced joy for Nagios config files in XEmacs Instant Classic (if you have to ask, you don't deserve to know ;).
  1. Browse to;a=blob_plain;f=nagios-mode.el;hb=HEAD
  2. Save file to something like ~/.xemacs/user_lisp/nagios-mode.el
  3. If you haven't already included ~/.xemacs/user_lisp in your load path, do so now by adding the following to your ~/.xemacs/custom.el:
    (add-to-list 'load-path "$HOME/.xemacs/user_lisp/")
  4. Now, load nagios-mode.el by adding the following to your ~/.xemacs/custom.el:
    (autoload 'nagios-mode "$HOME/.xemacs/user_lisp/nagios-mode.el"
    "Major mode for editing Nagios config files" t)
  5. Finally, you'll want nagios-mode.el automatically enabled for Nagios config files, so add the following to your ~/.xemacs/custom.el:
    ; nagios-mode
    (add-to-list 'auto-mode-alist
    '("nagios-config/objects/.+\\.cfg$" . nagios-mode))

You're welcome. ;)

Wednesday, April 06, 2011

Ruby Light #6

This is the most complicated bit of meta-programming in Ruby Light so far. Johan and I cooked it up; the beautiful plumbing is his, the basis of the instance_exec rebinding trick is mine.

The intent is as follows: for each request to a Rails controller, redirect unless all of the URL query parameters you get are valid.

And this is how it actually works:
  1. When Rails loads the FooController class:
    1. FooController mixes in the ParamsFilter module, resulting in it getting the known_params and parse_known_params class methods and the redirect_if_unknown_params and select_unknown instance methods (et al.).
    2. FooController calls the known_params class method to always accept the "limit" and "offset" params, but only accept the "bar" param when the Foo object is of type "bar".
  2. On each request:
    1. FooController's before_filter calls its redirect_if_unknown_params instance method.
    2. redirect_if_unknown_params rejects unknown parameters using the private select_unknown instance method.
    3. select_unknown calls known_param? on each param.
    4. If the param has a :when component, known_param? executes its value (which is a block)--and here's the cool part--in the context of the controller instance! This is cool because Proc objects normally operate in the context in which they were defined (i.e. they are closures). Calling instance_eval or instance_exec with a Proc argument (which is not the same thing as a block!) results in the Proc's binding being changed to context where it is called. This results in self, which was the FooController class when the Proc was defined, being set to the FooController instance on which known_param? is executing.

And now, the code:

class FooController < ApplicationController
include ParamsFilter

before_filter :redirect_if_unknown_params
known_params :limit, :offset, :only => :bar, :when => lambda {@type == 'bar'}
# [...]

module ParamsFilter
def self.included(base)
base.send :extend, ClassMethods
base.send :include, InstanceMethods

module ClassMethods
attr_reader :known_params

def known_params(*args, &block)
@@known_params ||=
@@known_params.merge! parse_known_params(*args, &block)

def parse_known_params(*args, &block) do |known_params|
options = (args.last.is_a? Hash) ? args.pop.dup : {}
options[:when] = block if block_given?

args.each do |param|
known_params[param] = options

module InstanceMethods
def known_params(*args)
@known_params ||=
@known_params.merge! self.class.parse_known_params(*args)

def redirect_if_unknown_params
unknown = select_unknown request.query_parameters, request.path_parameters
redirect_without_unknown_params unknown unless unknown.empty?


def select_unknown(query_params = {}, path_params = {})
query_params.reject {|param, _| known_param? param, path_params}

def known_param?(param, params)
if options = param_options(param)
if action_matches_params? options[:only], params
options[:when].nil? || instance_exec(param, &options[:when])

def redirect_without_unknown_params(unknown_params)
# Actually perform redirect

# [...]

Friday, April 01, 2011

Ruby Light #5

This is a remix of Ruby Light #1, done better (IMHO):

require 'stringio'

module RedirectIo
def setup
$stderr = @stderr =
$stdin = @stdin =
$stdout = @stdout =

def teardown
$stderr = STDERR
$stdin = STDIN
$stdout = STDOUT

require 'test_helper'
require 'lib/generic_test_helper.rb' # from Ruby Light #3
require 'lib/redirect_io'

class TimestampLoggerTest < Test::Unit::TestCase
include GenericTestHelper
include RedirectIo

LOG_LEVELS = [:error, :warn, :info, :debug]

def setup
super # RedirectIO.setup needs to run

@logger = $stdout
@logger.level = Logger::DEBUG

def test_timestamps
LOG_LEVELS.each do |level|
@logger.send level, 'foo'

@stdout.string.split("\n").each do |line|
assert_match /^#{TIMESTAMP_MATCHER} /, line

def test_labels
LOG_LEVELS.each do |level|
@logger.send level, 'foo'

[:error, :warn].each do |level|
assert_match /^#{TIMESTAMP_MATCHER} \[#{level.to_s.upcase}\] /, @stdout.string