Reads of Vagrant::ActiveList to track the active vagrant managed virtual environments.

This commit is contained in:
Mitchell Hashimoto 2010-03-14 16:08:58 -07:00
parent ab1acf2479
commit 235480fffa
2 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,40 @@
module Vagrant
# This class represents the active list of vagrant virtual
# machines.
class ActiveList
FILENAME = "active.json"
@@list = nil
class <<self
# Parses and returns the list of UUIDs from the active VM
# JSON file. This will cache the result, which can be reloaded
# by setting the `reload` parameter to true.
#
# @return [Array<String>]
def list(reload = false)
return @@list unless @@list.nil? || reload
@@list ||= []
return @@list unless File.file?(path)
File.open(path, "r") do |f|
@@list = JSON.parse(f.read)
end
@@list
end
# Returns an array of {Vagrant::VM} objects which are currently
# active.
def vms
list.collect { |uuid| Vagrant::VM.find(uuid) }
end
# Returns the path to the JSON file which holds the UUIDs of the
# active virtual machines managed by Vagrant.
def path
File.join(Env.home_path, FILENAME)
end
end
end
end

View File

@ -0,0 +1,71 @@
require File.join(File.dirname(__FILE__), '..', 'test_helper')
class ActiveListTest < Test::Unit::TestCase
setup do
mock_config
end
context "class methods" do
context "loading" do
should "load if reload is given" do
File.stubs(:file?).returns(true)
File.expects(:open).once
Vagrant::ActiveList.list(true)
end
should "not load if the active json file doesn't exist" do
File.expects(:file?).with(Vagrant::ActiveList.path).returns(false)
File.expects(:open).never
assert_equal [], Vagrant::ActiveList.list(true)
end
should "parse the JSON by reading the file" do
file = mock("file")
data = mock("data")
result = mock("result")
File.expects(:file?).returns(true)
File.expects(:open).with(Vagrant::ActiveList.path, 'r').once.yields(file)
file.expects(:read).returns(data)
JSON.expects(:parse).with(data).returns(result)
assert_equal result, Vagrant::ActiveList.list(true)
end
should "not load if reload flag is false and already loaded" do
File.expects(:file?).once.returns(false)
result = Vagrant::ActiveList.list(true)
assert result.equal?(Vagrant::ActiveList.list)
assert result.equal?(Vagrant::ActiveList.list)
assert result.equal?(Vagrant::ActiveList.list)
end
end
context "vms" do
setup do
@list = ["foo", "bar"]
Vagrant::ActiveList.stubs(:list).returns(@list)
end
should "return the list, but with each value as a VM" do
new_seq = sequence("new")
results = []
@list.each do |item|
result = mock("result-#{item}")
Vagrant::VM.expects(:find).with(item).returns(result).in_sequence(new_seq)
results << result
end
assert_equal results, Vagrant::ActiveList.vms
end
end
context "path" do
setup do
Vagrant::Env.stubs(:home_path).returns("foo")
end
should "return the active file within the home path" do
assert_equal File.join(Vagrant::Env.home_path, Vagrant::ActiveList::FILENAME), Vagrant::ActiveList.path
end
end
end
end