mongo-ruby-driver/bin/validate

52 lines
1.7 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env ruby
#
2009-01-09 22:30:04 +00:00
# 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.
#
2009-01-12 16:23:07 +00:00
# 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'
2009-01-12 16:23:07 +00:00
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
2009-01-09 22:30:04 +00:00
File.open(ARGV[1], 'wb') { |f| bson.each { |b| f.putc(b) } }
2009-01-12 16:23:07 +00:00
# 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