semanticart (owner)

Revisions

gist: 223631 Download_button fork
public
Public Clone URL: git://gist.github.com/223631.git
Embed All Files: show embed
mongo_ruby_driver_import_test.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# run the script and pass the path to your mongo/bin
# i.e.
# ruby mongodb_import_test.rb ~/Downloads/mongodb-osx-x86_64-1.0.1/bin
 
require 'rubygems'
require 'test/unit'
require 'mongo'
 
include Mongo
 
db = Connection.new('localhost').db('test-import')
Artist = db.collection('artists')
 
BIN_PATH = ARGV[0] || ""
 
raise "please specify the path to your mongo/bin directory" unless File.exist?(BIN_PATH + "/mongoimportjson")
 
class MongoSanityTest < Test::Unit::TestCase
  def setup
    Artist.remove
    @id = Artist.insert(:name => "SOME NAME")
  end
 
  def test_can_create_a_record
    assert !Artist.find_one(:_id => @id).nil?
  end
 
  def test_can_update_a_record
    Artist.update({:_id => @id}, {:_id => @id, :name => "new name"})
    assert_equal Artist.find_one(:_id => @id)["name"], "new name"
    # we have just one record since we did an update instead of an insert
    assert_equal Artist.count, 1
  end
end
 
class MongoImportTest < Test::Unit::TestCase
  
  def setup
    # drop our json import file which contains a single record
    File.open('out.json', 'w') do |f|
      f.puts %({ "_id" : "4aecaaa7f62c1923628c36a8", "name" : "IMPORTED RECORD" })
    end
 
    # do the actual importing and pass --drop to ensure the collection is emptied first
    `#{BIN_PATH}/mongoimportjson -d test-import --drop -c artists out.json`
 
    # ensure we imported our record properly
    assert Artist.find_one(:name => "IMPORTED RECORD")
    # and that there is only one
    assert_equal Artist.count, 1
  end
 
  def test_can_create_a_record_after_import
    id = Artist.insert(:name => "SOME NAME")
    assert !Artist.find(:_id => id).nil?
    assert_equal Artist.count, 2
 end
 
  def test_can_update_a_record_after_import
    artist = Artist.find_one(:name => "IMPORTED RECORD")
    assert artist
 
    # we rename our artist
    Artist.update({:_id => artist["_id"]}, {:_id => artist["_id"], :name => "new name"})
    # we check that the name was updated
    assert_equal Artist.find_one(:_id => artist["_id"])["name"], "new name"
 
    assert_equal Artist.count, 1
  end
 
  def test_that_we_can_update_the_name_natively
    # use the mongo binary to update the name
    `#{BIN_PATH}/mongo test-import --eval "db.artists.update({name: 'IMPORTED RECORD'}, {name: 'new name'});"`
    # we have a record matching 'new name'
    assert_equal Artist.find_one["name"], 'new name'
    # we only have one record
    assert_equal Artist.count, 1
  end
end