mongo-ruby-driver/bin/validate
2009-01-12 11:23:07 -05:00

52 lines
1.7 KiB
Ruby
Executable File

#!/usr/bin/env ruby
#
# usage: validate somefile.xson somefile.bson
#
# Reads somefile.xson file (XML that describes a Mongo-type document),
# converts it into a Ruby OrderedHash, runs that through the BSON
# serialization code, and writes the BSON bytes to somefile.bson.
#
# In addition, this script takes the generated BSON, reads it in then writes
# it back out to a temp BSON file. If they are different, we report that error
# to STDOUT.
#
# This script is used by the mongo-qa project
# (http://github.com/mongodb/mongo-qa).
$LOAD_PATH[0,0] = File.join(File.dirname(__FILE__), '..', 'lib')
require 'mongo'
require 'mongo/util/xml_to_ruby'
if ARGV.length < 2
$stderr.puts "usage: validate somefile.xson somefile.bson"
exit 1
end
# Translate the .xson XML into a Ruby object, turn that object into BSON, and
# write the BSON to the file as requested.
obj = File.open(ARGV[0], 'rb') { |f| XMLToRuby.new.xml_to_ruby(f) }
bson = BSON.new.serialize(obj).to_a
File.open(ARGV[1], 'wb') { |f| bson.each { |b| f.putc(b) } }
# Now the additional testing. Read the generated BSON back in, deserialize it,
# and re-serialize the results. Compare that BSON with the BSON from the file
# we output.
bson = File.open(ARGV[1], 'rb') { |f| f.read }
bson = if RUBY_VERSION >= '1.9'
bson.bytes.to_a
else
bson.split(//).collect { |c| c[0] }
end
# Turn the Ruby object into BSON bytes and compare with the BSON bytes from
# the file.
bson_from_ruby = BSON.new.serialize(obj).to_a
if bson.length != bson_from_ruby.length
$stderr.puts "error: round-trip BSON lengths differ when testing #{ARGV[0]}"
exit 1
elsif bson != bson_from_ruby
$stderr.puts "error: round-trip BSON contents differ when testing #{ARGV[0]}"
exit 1
end