Merge pull request #7355 from mitchellh/sethvargo/tmpfile

Identify and cleanup tempfiles and temporary directories
This commit is contained in:
Seth Vargo 2016-05-29 00:46:37 -04:00
commit 9a2f6bd63d
55 changed files with 635 additions and 324 deletions

View File

@ -118,7 +118,7 @@ module Vagrant
# @param [Hash] download_options Options to pass to the downloader. # @param [Hash] download_options Options to pass to the downloader.
# @return [BoxMetadata] # @return [BoxMetadata]
def load_metadata(**download_options) def load_metadata(**download_options)
tf = Tempfile.new("vagrant") tf = Tempfile.new("vagrant-load-metadata")
tf.close tf.close
url = @metadata_url url = @metadata_url

View File

@ -56,7 +56,7 @@ module Vagrant
# Setup the "local" Bundler configuration. We need to set BUNDLE_PATH # Setup the "local" Bundler configuration. We need to set BUNDLE_PATH
# because the existence of this actually suppresses `sudo`. # because the existence of this actually suppresses `sudo`.
@appconfigpath = Dir.mktmpdir @appconfigpath = Dir.mktmpdir("vagrant-bundle-app-config")
File.open(File.join(@appconfigpath, "config"), "w+") do |f| File.open(File.join(@appconfigpath, "config"), "w+") do |f|
f.write("BUNDLE_PATH: \"#{bundle_path}\"") f.write("BUNDLE_PATH: \"#{bundle_path}\"")
end end

View File

@ -9,6 +9,7 @@ module Vagrant
autoload :SafeExec, 'vagrant/util/safe_exec' autoload :SafeExec, 'vagrant/util/safe_exec'
autoload :StackedProcRunner, 'vagrant/util/stacked_proc_runner' autoload :StackedProcRunner, 'vagrant/util/stacked_proc_runner'
autoload :TemplateRenderer, 'vagrant/util/template_renderer' autoload :TemplateRenderer, 'vagrant/util/template_renderer'
autoload :Tempfile, 'vagrant/util/tempfile'
autoload :Subprocess, 'vagrant/util/subprocess' autoload :Subprocess, 'vagrant/util/subprocess'
end end
end end

View File

@ -125,7 +125,7 @@ module Vagrant
# directory runs a different filesystem than the root directory. # directory runs a different filesystem than the root directory.
# However, this works in many cases. # However, this works in many cases.
def fs_case_sensitive? def fs_case_sensitive?
Dir.mktmpdir("vagrant") do |tmp_dir| Dir.mktmpdir("vagrant-fs-case-sensitive") do |tmp_dir|
tmp_file = File.join(tmp_dir, "FILE") tmp_file = File.join(tmp_dir, "FILE")
File.open(tmp_file, "w") do |f| File.open(tmp_file, "w") do |f|
f.write("foo") f.write("foo")

View File

@ -0,0 +1,58 @@
require "tempfile"
module Vagrant
module Util
class Tempfile
# Utility function for creating a temporary file that will persist for
# the duration of the block and then be removed after the block finishes.
#
# @example
#
# Tempfile.create("arch-configure-networks") do |f|
# f.write("network-1")
# f.fsync
# f.close
# do_something_with_file(f.path)
# end
#
# @example
#
# Tempfile.create(["runner", "ps1"]) do |f|
# # f will have a suffix of ".ps1"
# # ...
# end
#
# @param [String, Array] name the prefix of the tempfile to create
# @param [Hash] options a list of options
# @param [Proc] block the block to yield the file object to
#
# @yield [File]
def self.create(name, options = {})
raise "No block given!" if !block_given?
options = {
binmode: true
}.merge(options)
# The user can specify an array where the first parameter is the prefix
# and the last parameter is the file suffix. We want to prefix the
# "prefix" with `vagrant-`, and this does that
if name.is_a?(Array)
basename = ["vagrant-#{name[0]}", name[1]]
else
basename = "vagrant-#{name}"
end
Dir::Tmpname.create(basename) do |path|
begin
f = File.open(path, "w+")
f.binmode if options[:binmode]
yield f
ensure
File.unlink(f.path) if File.file?(f.path)
end
end
end
end
end
end

View File

@ -5,11 +5,14 @@ require "log4r"
require_relative "helper" require_relative "helper"
require_relative "shell" require_relative "shell"
require_relative "command_filter" require_relative "command_filter"
require_relative "../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module CommunicatorWinRM module CommunicatorWinRM
# Provides communication channel for Vagrant commands via WinRM. # Provides communication channel for Vagrant commands via WinRM.
class Communicator < Vagrant.plugin("2", :communicator) class Communicator < Vagrant.plugin("2", :communicator)
include Vagrant::Util
def self.match?(machine) def self.match?(machine)
# This is useless, and will likely be removed in the future (this # This is useless, and will likely be removed in the future (this
# whole method). # whole method).
@ -202,15 +205,11 @@ module VagrantPlugins
interactive: interactive, interactive: interactive,
}) })
guest_script_path = "c:/tmp/vagrant-elevated-shell.ps1" guest_script_path = "c:/tmp/vagrant-elevated-shell.ps1"
file = Tempfile.new(["vagrant-elevated-shell", "ps1"]) Tempfile.create(["vagrant-elevated-shell", "ps1"]) do |f|
begin f.write(script)
file.write(script) f.fsync
file.fsync f.close
file.close upload(f.path, guest_script_path)
upload(file.path, guest_script_path)
ensure
file.close
file.unlink
end end
# Convert to double byte unicode string then base64 encode # Convert to double byte unicode string then base64 encode

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestArch module GuestArch
@ -10,23 +9,29 @@ module VagrantPlugins
include Vagrant::Util include Vagrant::Util
def self.configure_networks(machine, networks) def self.configure_networks(machine, networks)
interfaces = Array.new tempfiles = []
interfaces = []
machine.communicate.sudo("ip -o -0 addr | grep -v LOOPBACK | awk '{print $2}' | sed 's/://'") do |_, result| machine.communicate.sudo("ip -o -0 addr | grep -v LOOPBACK | awk '{print $2}' | sed 's/://'") do |_, result|
interfaces = result.split("\n") interfaces = result.split("\n")
end end
networks.each do |network| networks.each.with_index do |network, i|
network[:device] = interfaces[network[:interface]] network[:device] = interfaces[network[:interface]]
entry = TemplateRenderer.render("guests/arch/network_#{network[:type]}", options: network) entry = TemplateRenderer.render("guests/arch/network_#{network[:type]}",
options: network)
temp = Tempfile.new("vagrant") remote_path = "/tmp/vagrant-network-#{Time.now.to_i}-#{i}"
temp.binmode
temp.write(entry)
temp.close
machine.communicate.upload(temp.path, "/tmp/vagrant_network") Tempfile.create("arch-configure-networks") do |f|
machine.communicate.sudo("mv /tmp/vagrant_network /etc/netctl/#{network[:device]}") f.write(entry)
f.fsync
f.close
machine.communicate.upload(f.path, remote_path)
end
machine.communicate.sudo("mv #{remote_path} /etc/netctl/#{network[:device]}")
machine.communicate.sudo("ip link set #{network[:device]} down && netctl restart #{network[:device]} && netctl enable #{network[:device]}") machine.communicate.sudo("ip link set #{network[:device]} down && netctl restart #{network[:device]} && netctl enable #{network[:device]}")
end end
end end

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestCoreOS module GuestCoreOS
@ -54,11 +53,11 @@ module VagrantPlugins
}) })
end end
Tempfile.open("vagrant") do |temp| Tempfile.create("coreos-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
comm.upload(temp.path, "/tmp/etcd-cluster.service") comm.upload(f.path, "/tmp/etcd-cluster.service")
end end
comm.sudo("mv /tmp/etcd-cluster.service /media/state/units/") comm.sudo("mv /tmp/etcd-cluster.service /media/state/units/")

View File

@ -1,7 +1,7 @@
require 'set' require "set"
require 'tempfile'
require "vagrant/util/template_renderer" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module GuestDebian module GuestDebian
@ -29,14 +29,14 @@ module VagrantPlugins
entries << entry entries << entry
end end
# Perform the careful dance necessary to reconfigure # Perform the careful dance necessary to reconfigure the network
# the network interfaces # interfaces.
temp = Tempfile.new("vagrant") Tempfile.create("debian-configure-networks") do |f|
temp.binmode f.write(entries.join("\n"))
temp.write(entries.join("\n")) f.fsync
temp.close f.close
comm.upload(f.path, "/tmp/vagrant-network-entry")
comm.upload(temp.path, "/tmp/vagrant-network-entry") end
# Bring down all the interfaces we're reconfiguring. By bringing down # Bring down all the interfaces we're reconfiguring. By bringing down
# each specifically, we avoid reconfiguring eth0 (the NAT interface) so # each specifically, we avoid reconfiguring eth0 (the NAT interface) so

View File

@ -1,8 +1,8 @@
require "set" require "set"
require "tempfile"
require "vagrant/util/retryable" require_relative "../../../../lib/vagrant/util/retryable"
require "vagrant/util/template_renderer" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module GuestFedora module GuestFedora
@ -96,12 +96,12 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/fedora/network_#{network[:type]}", entry = TemplateRenderer.render("guests/fedora/network_#{network[:type]}",
options: network) options: network)
temp = Tempfile.new("vagrant") Tempfile.create("fedora-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant-network-entry_#{interface}")
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry_#{interface}") end
end end
# Bring down all the interfaces we're reconfiguring. By bringing down # Bring down all the interfaces we're reconfiguring. By bringing down

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestFreeBSD module GuestFreeBSD
@ -29,13 +28,13 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/freebsd/network_#{network[:type]}", entry = TemplateRenderer.render("guests/freebsd/network_#{network[:type]}",
options: network, ifname: ifname) options: network, ifname: ifname)
# Write the entry to a temporary location Tempfile.create("freebsd-configure-networks") do |f|
temp = Tempfile.new("vagrant") f.write(entry)
temp.binmode f.fsync
temp.write(entry) f.close
temp.close machine.communicate.upload(f.path, "/tmp/vagrant-network-entry")
end
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry")
machine.communicate.sudo("su -m root -c 'cat /tmp/vagrant-network-entry >> /etc/rc.conf'", {shell: "sh"}) machine.communicate.sudo("su -m root -c 'cat /tmp/vagrant-network-entry >> /etc/rc.conf'", {shell: "sh"})
machine.communicate.sudo("rm -f /tmp/vagrant-network-entry", {shell: "sh"}) machine.communicate.sudo("rm -f /tmp/vagrant-network-entry", {shell: "sh"})

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestFuntoo module GuestFuntoo
@ -23,12 +22,15 @@ module VagrantPlugins
ifFile = "netif.eth#{network[:interface]}" ifFile = "netif.eth#{network[:interface]}"
entry = TemplateRenderer.render("guests/funtoo/network_#{network[:type]}", entry = TemplateRenderer.render("guests/funtoo/network_#{network[:type]}",
options: network) options: network)
# Upload the entry to a temporary location # Upload the entry to a temporary location
temp = Tempfile.new("vagrant") Tempfile.create("funtoo-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
comm.upload(temp.path, "/tmp/vagrant-#{ifFile}") comm.upload(f.path, "/tmp/vagrant-#{ifFile}")
end
comm.sudo("cp /tmp/vagrant-#{ifFile} /etc/conf.d/#{ifFile}") comm.sudo("cp /tmp/vagrant-#{ifFile} /etc/conf.d/#{ifFile}")
comm.sudo("chmod 0644 /etc/conf.d/#{ifFile}") comm.sudo("chmod 0644 /etc/conf.d/#{ifFile}")
comm.sudo("ln -fs /etc/init.d/netif.tmpl /etc/init.d/#{ifFile}") comm.sudo("ln -fs /etc/init.d/netif.tmpl /etc/init.d/#{ifFile}")

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestGentoo module GuestGentoo
@ -21,12 +20,12 @@ module VagrantPlugins
options: network) options: network)
# Upload the entry to a temporary location # Upload the entry to a temporary location
temp = Tempfile.new("vagrant") Tempfile.create("gentoo-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
comm.upload(f.path, "/tmp/vagrant-network-entry")
comm.upload(temp.path, "/tmp/vagrant-network-entry") end
# Configure the interface # Configure the interface
comm.sudo("ln -fs /etc/init.d/net.lo /etc/init.d/net.eth#{network[:interface]}") comm.sudo("ln -fs /etc/init.d/net.lo /etc/init.d/net.eth#{network[:interface]}")

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestNetBSD module GuestNetBSD
@ -20,13 +19,13 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/netbsd/network_#{network[:type]}", entry = TemplateRenderer.render("guests/netbsd/network_#{network[:type]}",
options: network) options: network)
temp = Tempfile.new("vagrant") Tempfile.create("netbsd-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant-network-entry")
end
# upload it and append it to the new rc.conf file
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry")
machine.communicate.sudo("cat /tmp/vagrant-network-entry >> #{newrcconf}") machine.communicate.sudo("cat /tmp/vagrant-network-entry >> #{newrcconf}")
machine.communicate.sudo("rm -f /tmp/vagrant-network-entry") machine.communicate.sudo("rm -f /tmp/vagrant-network-entry")
@ -45,7 +44,6 @@ module VagrantPlugins
# install new rc.conf # install new rc.conf
machine.communicate.sudo("install -c -o 0 -g 0 -m 644 #{newrcconf} /etc/rc.conf") machine.communicate.sudo("install -c -o 0 -g 0 -m 644 #{newrcconf} /etc/rc.conf")
end end
end end
end end

View File

@ -1,6 +1,5 @@
require 'tempfile' require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestNixos module GuestNixos
@ -16,13 +15,15 @@ module VagrantPlugins
# Upload a file. # Upload a file.
def self.upload(machine, content, remote_path) def self.upload(machine, content, remote_path)
local_temp = Tempfile.new("vagrant-upload")
local_temp.binmode
local_temp.write(content)
local_temp.close
remote_temp = mktemp(machine) remote_temp = mktemp(machine)
machine.communicate.upload(local_temp.path, "#{remote_temp}")
local_temp.delete Tempfile.create("nixos-change-host-name") do |f|
f.write(content)
f.fsync
f.close
machine.communicate.upload(f.path, "#{remote_temp}")
end
machine.communicate.sudo("mv #{remote_temp} #{remote_path}") machine.communicate.sudo("mv #{remote_temp} #{remote_path}")
end end

View File

@ -1,7 +1,7 @@
require 'tempfile' require "ipaddr"
require 'ipaddr'
require "vagrant/util/template_renderer" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module GuestNixos module GuestNixos
@ -65,13 +65,15 @@ module VagrantPlugins
# Upload a file. # Upload a file.
def self.upload(machine, content, remote_path) def self.upload(machine, content, remote_path)
local_temp = Tempfile.new("vagrant-upload")
local_temp.binmode
local_temp.write(content)
local_temp.close
remote_temp = mktemp(machine) remote_temp = mktemp(machine)
machine.communicate.upload(local_temp.path, "#{remote_temp}")
local_temp.delete Tempfile.create("nixos-configure-networks") do |f|
f.write(content)
f.fsync
f.close
machine.communicate.upload(f.path, "#{remote_temp}")
end
machine.communicate.sudo("mv #{remote_temp} #{remote_path}") machine.communicate.sudo("mv #{remote_temp} #{remote_path}")
end end

View File

@ -1,6 +1,5 @@
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestOpenBSD module GuestOpenBSD
@ -13,10 +12,12 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/openbsd/network_#{network[:type]}", entry = TemplateRenderer.render("guests/openbsd/network_#{network[:type]}",
options: network) options: network)
temp = Tempfile.new("vagrant") Tempfile.create("openbsd-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant-network-entry")
end
# Determine the interface prefix... # Determine the interface prefix...
command = "ifconfig -a | grep -o ^[0-9a-z]*" command = "ifconfig -a | grep -o ^[0-9a-z]*"
@ -31,7 +32,6 @@ module VagrantPlugins
end end
end end
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry")
machine.communicate.sudo("mv /tmp/vagrant-network-entry /etc/hostname.#{ifname}") machine.communicate.sudo("mv /tmp/vagrant-network-entry /etc/hostname.#{ifname}")
# remove old configurations # remove old configurations

View File

@ -1,8 +1,8 @@
require "set" require "set"
require "tempfile"
require "vagrant/util/retryable" require_relative "../../../../lib/vagrant/util/retryable"
require "vagrant/util/template_renderer" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module GuestRedHat module GuestRedHat
@ -55,12 +55,12 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/redhat/network_#{network[:type]}", entry = TemplateRenderer.render("guests/redhat/network_#{network[:type]}",
options: network) options: network)
temp = Tempfile.new("vagrant") Tempfile.create("red-hat-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant-network-entry_#{network[:interface]}")
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry_#{network[:interface]}") end
end end
# Bring down all the interfaces we're reconfiguring. By bringing down # Bring down all the interfaces we're reconfiguring. By bringing down

View File

@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
require "tempfile" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
module VagrantPlugins module VagrantPlugins
module GuestSlackware module GuestSlackware
@ -20,15 +19,16 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/slackware/network_#{network[:type]}", options: network) entry = TemplateRenderer.render("guests/slackware/network_#{network[:type]}", options: network)
temp = Tempfile.new("vagrant") Tempfile.create("slackware-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant_network")
end
machine.communicate.upload(temp.path, "/tmp/vagrant_network")
machine.communicate.sudo("mv /tmp/vagrant_network /etc/rc.d/rc.inet1.conf") machine.communicate.sudo("mv /tmp/vagrant_network /etc/rc.d/rc.inet1.conf")
machine.communicate.sudo("/etc/rc.d/rc.inet1") machine.communicate.sudo("/etc/rc.d/rc.inet1")
end end
end end
end end
end end

View File

@ -1,8 +1,8 @@
require "set" require "set"
require "tempfile"
require "vagrant/util/retryable" require_relative "../../../../lib/vagrant/util/retryable"
require "vagrant/util/template_renderer" require_relative "../../../../lib/vagrant/util/template_renderer"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module GuestSUSE module GuestSUSE
@ -33,12 +33,12 @@ module VagrantPlugins
entry = TemplateRenderer.render("guests/suse/network_#{network[:type]}", entry = TemplateRenderer.render("guests/suse/network_#{network[:type]}",
options: network) options: network)
temp = Tempfile.new("vagrant") Tempfile.create("suse-configure-networks") do |f|
temp.binmode f.write(entry)
temp.write(entry) f.fsync
temp.close f.close
machine.communicate.upload(f.path, "/tmp/vagrant-network-entry_#{network[:interface]}")
machine.communicate.upload(temp.path, "/tmp/vagrant-network-entry_#{network[:interface]}") end
end end
# Bring down all the interfaces we're reconfiguring. By bringing down # Bring down all the interfaces we're reconfiguring. By bringing down

View File

@ -16,8 +16,7 @@ module VagrantPlugins
SHA256SUM = "62f933115498e51ddf5f2dab47dc1eebb42eb78ea1a7665cb91c53edacc847c6".freeze SHA256SUM = "62f933115498e51ddf5f2dab47dc1eebb42eb78ea1a7665cb91c53edacc847c6".freeze
def self.provider_install_virtualbox(env) def self.provider_install_virtualbox(env)
tf = Tempfile.new("vagrant") path = Dir::Tmpname.create("vagrant-provider-install-virtualbox") {}
tf.close
# Prefixed UI for prettiness # Prefixed UI for prettiness
ui = Vagrant::UI::Prefixed.new(env.ui, "") ui = Vagrant::UI::Prefixed.new(env.ui, "")
@ -28,11 +27,11 @@ module VagrantPlugins
version: VERSION)) version: VERSION))
ui.detail(I18n.t( ui.detail(I18n.t(
"vagrant.hosts.darwin.virtualbox_install_detail")) "vagrant.hosts.darwin.virtualbox_install_detail"))
dl = Vagrant::Util::Downloader.new(URL, tf.path, ui: ui) dl = Vagrant::Util::Downloader.new(URL, path, ui: ui)
dl.download! dl.download!
# Validate that the file checksum matches # Validate that the file checksum matches
actual = FileChecksum.new(tf.path, Digest::SHA2).checksum actual = FileChecksum.new(path, Digest::SHA2).checksum
if actual != SHA256SUM if actual != SHA256SUM
raise Vagrant::Errors::ProviderChecksumMismatch, raise Vagrant::Errors::ProviderChecksumMismatch,
provider: "virtualbox", provider: "virtualbox",
@ -46,7 +45,7 @@ module VagrantPlugins
ui.detail(I18n.t( ui.detail(I18n.t(
"vagrant.hosts.darwin.virtualbox_install_install_detail")) "vagrant.hosts.darwin.virtualbox_install_install_detail"))
script = File.expand_path("../../scripts/install_virtualbox.sh", __FILE__) script = File.expand_path("../../scripts/install_virtualbox.sh", __FILE__)
result = Vagrant::Util::Subprocess.execute("bash", script, tf.path) result = Vagrant::Util::Subprocess.execute("bash", script, path)
if result.exit_code != 0 if result.exit_code != 0
raise Vagrant::Errors::ProviderInstallFailed, raise Vagrant::Errors::ProviderInstallFailed,
provider: "virtualbox", provider: "virtualbox",

View File

@ -9,7 +9,18 @@ module VagrantPlugins
class RDP class RDP
def self.rdp_client(env, rdp_info) def self.rdp_client(env, rdp_info)
config_path = self.generate_config_file(rdp_info) config_path = self.generate_config_file(rdp_info)
Vagrant::Util::Subprocess.execute("open", config_path.to_s) begin
Vagrant::Util::Subprocess.execute("open", config_path.to_s)
ensure
# Note: this technically will never get run; neither would an
# at_exit call. The reason is that `exec` replaces this process,
# effectively the same as `kill -9`. This is solely here to prove
# that and so that future developers do not waste a ton of time
# try to identify why Vagrant is leaking RDP connection files.
# There is a catch-22 here in that we can't delete the file before
# we exec, and we can't delete the file after we exec :(.
File.unlink(config_path) if File.file?(config_path)
end
end end
protected protected
@ -25,21 +36,24 @@ module VagrantPlugins
} }
# Create the ".rdp" file # Create the ".rdp" file
config_path = Pathname.new(Dir.tmpdir).join( t = ::Tempfile.new(["vagrant-rdp", ".rdp"]).tap do |f|
"vagrant-rdp-#{Time.now.to_i}-#{rand(10000)}.rdp") f.binmode
config_path.open("w+") do |f|
opts.each do |k, v| opts.each do |k, v|
f.puts("#{k}:#{v}") f.write("#{k}:#{v}")
end end
if rdp_info[:extra_args] if rdp_info[:extra_args]
rdp_info[:extra_args].each do |arg| rdp_info[:extra_args].each do |arg|
f.puts("#{arg}") f.write("#{arg}")
end end
end end
f.fsync
f.close
end end
return config_path return t.path
end end
end end
end end

View File

@ -17,8 +17,7 @@ module VagrantPlugins
SHA256SUM = "3e5ed8fe4ada6eef8dfb4fe6fd79fcab4b242acf799f7d3ab4a17b43838b1e04".freeze SHA256SUM = "3e5ed8fe4ada6eef8dfb4fe6fd79fcab4b242acf799f7d3ab4a17b43838b1e04".freeze
def self.provider_install_virtualbox(env) def self.provider_install_virtualbox(env)
tf = Tempfile.new("vagrant") path = Dir::Tmpname.create("vagrant-provider-install-virtualbox") {}
tf.close
# Prefixed UI for prettiness # Prefixed UI for prettiness
ui = Vagrant::UI::Prefixed.new(env.ui, "") ui = Vagrant::UI::Prefixed.new(env.ui, "")
@ -29,11 +28,11 @@ module VagrantPlugins
version: VERSION)) version: VERSION))
ui.detail(I18n.t( ui.detail(I18n.t(
"vagrant.hosts.windows.virtualbox_install_detail")) "vagrant.hosts.windows.virtualbox_install_detail"))
dl = Vagrant::Util::Downloader.new(URL, tf.path, ui: ui) dl = Vagrant::Util::Downloader.new(URL, path, ui: ui)
dl.download! dl.download!
# Validate that the file checksum matches # Validate that the file checksum matches
actual = FileChecksum.new(tf.path, Digest::SHA2).checksum actual = FileChecksum.new(path, Digest::SHA2).checksum
if actual != SHA256SUM if actual != SHA256SUM
raise Vagrant::Errors::ProviderChecksumMismatch, raise Vagrant::Errors::ProviderChecksumMismatch,
provider: "virtualbox", provider: "virtualbox",
@ -47,7 +46,7 @@ module VagrantPlugins
ui.detail(I18n.t( ui.detail(I18n.t(
"vagrant.hosts.windows.virtualbox_install_install_detail")) "vagrant.hosts.windows.virtualbox_install_install_detail"))
script = File.expand_path("../../scripts/install_virtualbox.ps1", __FILE__) script = File.expand_path("../../scripts/install_virtualbox.ps1", __FILE__)
result = Vagrant::Util::PowerShell.execute(script, tf.path) result = Vagrant::Util::PowerShell.execute(script, path)
if result.exit_code != 0 if result.exit_code != 0
raise Vagrant::Errors::ProviderInstallFailed, raise Vagrant::Errors::ProviderInstallFailed,
provider: "virtualbox", provider: "virtualbox",

View File

@ -14,7 +14,7 @@ module VagrantPlugins
def call(env) def call(env)
env["package.output"] ||= "package.box" env["package.output"] ||= "package.box"
env["package.directory"] ||= Dir.mktmpdir("package-", env[:tmp_path]) env["package.directory"] ||= Dir.mktmpdir("vagrant-package-", env[:tmp_path])
# Match up a couple environmental variables so that the other parts of # Match up a couple environmental variables so that the other parts of
# Vagrant will do the right thing. # Vagrant will do the right thing.

View File

@ -1,11 +1,11 @@
require 'tempfile'
require_relative "base" require_relative "base"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module Ansible module Ansible
module Provisioner module Provisioner
class Guest < Base class Guest < Base
include Vagrant::Util
def initialize(machine, config) def initialize(machine, config)
super super
@ -103,14 +103,14 @@ module VagrantPlugins
inventory_basedir = File.join(config.tmp_path, "inventory") inventory_basedir = File.join(config.tmp_path, "inventory")
inventory_path = File.join(inventory_basedir, "vagrant_ansible_local_inventory") inventory_path = File.join(inventory_basedir, "vagrant_ansible_local_inventory")
temp_inventory = Tempfile.new("vagrant_ansible_local_inventory_#{@machine.name}")
temp_inventory.write(inventory_content)
temp_inventory.close
create_and_chown_remote_folder(inventory_basedir) create_and_chown_remote_folder(inventory_basedir)
@machine.communicate.tap do |comm| @machine.communicate.sudo("rm -f #{inventory_path}", error_check: false)
comm.sudo("rm -f #{inventory_path}", error_check: false)
comm.upload(temp_inventory.path, inventory_path) Tempfile.create("ansible-local-inventory-#{@machine.name}") do |f|
f.write(inventory_content)
f.fsync
f.close
@machine.communicate.upload(f.path, inventory_path)
end end
return inventory_basedir return inventory_basedir

View File

@ -1,7 +1,6 @@
require 'tempfile' require_relative "../../../../lib/vagrant/util/presence"
require_relative "../../../../lib/vagrant/util/template_renderer"
require "vagrant/util/presence" require_relative "../../../../lib/vagrant/util/tempfile"
require "vagrant/util/template_renderer"
require_relative "../installer" require_relative "../installer"
@ -12,6 +11,7 @@ module VagrantPlugins
# chef-solo and chef-client provisioning are stored. This is **not an actual # chef-solo and chef-client provisioning are stored. This is **not an actual
# provisioner**. Instead, {ChefSolo} or {ChefServer} should be used. # provisioner**. Instead, {ChefSolo} or {ChefServer} should be used.
class Base < Vagrant.plugin("2", :provisioner) class Base < Vagrant.plugin("2", :provisioner)
include Vagrant::Util
include Vagrant::Util::Presence include Vagrant::Util::Presence
class ChefError < Vagrant::Errors::VagrantError class ChefError < Vagrant::Errors::VagrantError
@ -118,7 +118,7 @@ module VagrantPlugins
@machine.communicate.upload(expanded, remote_custom_config_path) @machine.communicate.upload(expanded, remote_custom_config_path)
end end
config_file = Vagrant::Util::TemplateRenderer.render(template, { config_file = TemplateRenderer.render(template, {
custom_configuration: remote_custom_config_path, custom_configuration: remote_custom_config_path,
encrypted_data_bag_secret: guest_encrypted_data_bag_secret_key_path, encrypted_data_bag_secret: guest_encrypted_data_bag_secret_key_path,
environment: @config.environment, environment: @config.environment,
@ -138,16 +138,14 @@ module VagrantPlugins
formatter: @config.formatter formatter: @config.formatter
}.merge(template_vars)) }.merge(template_vars))
# Create a temporary file to store the data so we # Create a temporary file to store the data so we can upload it.
# can upload it
temp = Tempfile.new("vagrant")
temp.write(config_file)
temp.close
remote_file = File.join(guest_provisioning_path, filename) remote_file = File.join(guest_provisioning_path, filename)
@machine.communicate.tap do |comm| @machine.communicate.sudo(remove_command(remote_file), error_check: false)
comm.sudo("rm -f #{remote_file}", error_check: false) Tempfile.create("chef-provisioner-config") do |f|
comm.upload(temp.path, remote_file) f.write(config_file)
f.fsync
f.close
@machine.communicate.upload(f.path, remote_file)
end end
end end
@ -160,22 +158,14 @@ module VagrantPlugins
!@config.run_list.empty? !@config.run_list.empty?
json = JSON.pretty_generate(json) json = JSON.pretty_generate(json)
# Create a temporary file to store the data so we # Create a temporary file to store the data so we can upload it.
# can upload it
temp = Tempfile.new("vagrant")
temp.write(json)
temp.close
remote_file = File.join(guest_provisioning_path, "dna.json") remote_file = File.join(guest_provisioning_path, "dna.json")
@machine.communicate.tap do |comm| @machine.communicate.sudo(remove_command(remote_file), error_check: false)
if windows? Tempfile.create("chef-provisioner-config") do |f|
command = "if (test-path '#{remote_file}') {rm '#{remote_file}' -force -recurse}" f.write(json)
else f.fsync
command = "rm -f #{remote_file}" f.close
end @machine.communicate.upload(f.path, remote_file)
comm.sudo(command, error_check: false)
comm.upload(temp.path, remote_file)
end end
end end
@ -186,29 +176,15 @@ module VagrantPlugins
@machine.ui.info I18n.t( @machine.ui.info I18n.t(
"vagrant.provisioners.chef.upload_encrypted_data_bag_secret_key") "vagrant.provisioners.chef.upload_encrypted_data_bag_secret_key")
@machine.communicate.tap do |comm| @machine.communicate.sudo(remove_command(remote_file), error_check: false)
if windows? @machine.communicate.upload(encrypted_data_bag_secret_key_path, remote_file)
command = "if (test-path ""#{remote_file}"") {rm ""#{remote_file}"" -force -recurse}"
else
command = "rm -f #{remote_file}"
end
comm.sudo(command, error_check: false)
comm.upload(encrypted_data_bag_secret_key_path, remote_file)
end
end end
def delete_encrypted_data_bag_secret def delete_encrypted_data_bag_secret
remote_file = guest_encrypted_data_bag_secret_key_path remote_file = guest_encrypted_data_bag_secret_key_path
if remote_file return if remote_file.nil?
if windows?
command = "if (test-path ""#{remote_file}"") {rm ""#{remote_file}"" -force -recurse}"
else
command = "rm -f #{remote_file}"
end
@machine.communicate.sudo(command, error_check: false) @machine.communicate.sudo(remove_command(remote_file), error_check: false)
end
end end
def encrypted_data_bag_secret_key_path def encrypted_data_bag_secret_key_path
@ -258,6 +234,14 @@ module VagrantPlugins
end end
end end
def remove_command(path)
if windows?
"if (test-path ""#{path}"") {rm ""#{path}"" -force -recurse}"
else
"rm -f #{path}"
end
end
def windows? def windows?
@machine.config.vm.communicator == :winrm @machine.config.vm.communicator == :winrm
end end

View File

@ -1,7 +1,7 @@
require "digest/md5" require "digest/md5"
require "tempfile"
require_relative "base" require_relative "base"
require_relative "../../../../lib/vagrant/util/tempfile"
module VagrantPlugins module VagrantPlugins
module Chef module Chef
@ -54,17 +54,15 @@ module VagrantPlugins
# Write the raw recipe contents to a tempfile and upload that to the # Write the raw recipe contents to a tempfile and upload that to the
# machine. # machine.
def upload_recipe def upload_recipe
# Write the raw recipe contents to a tempfile # Write the raw recipe contents to a tempfile and upload
file = Tempfile.new(["vagrant-chef-apply", ".rb"]) Tempfile.create(["chef-apply", ".rb"]) do |f|
file.write(config.recipe) f.write(config.recipe)
file.rewind f.fsync
f.close
# Upload the tempfile to the guest # Upload the tempfile to the guest
@machine.communicate.upload(file.path, target_recipe_path) @machine.communicate.upload(f.path, target_recipe_path)
ensure end
# Delete our template
file.close
file.unlink
end end
end end
end end

View File

@ -28,7 +28,7 @@ class IsolatedEnvironment
@logger = Log4r::Logger.new("test::isolated_environment") @logger = Log4r::Logger.new("test::isolated_environment")
# Create a temporary directory for our work # Create a temporary directory for our work
@tempdir = Vagrant::Util::Platform.fs_real_path(Dir.mktmpdir("vagrant")) @tempdir = Vagrant::Util::Platform.fs_real_path(Dir.mktmpdir("vagrant-iso-env"))
@logger.info("Initialize isolated environment: #{@tempdir}") @logger.info("Initialize isolated environment: #{@tempdir}")
# Setup the home and working directories # Setup the home and working directories

View File

@ -27,6 +27,10 @@ require "unit/support/shared/virtualbox_context"
$stdout.sync = true $stdout.sync = true
$stderr.sync = true $stderr.sync = true
# Create a temporary directory where test vagrant will run. The reason we save
# this to a constant is so we can clean it up later.
VAGRANT_TEST_CWD = Dir.mktmpdir("vagrant-test-cwd")
# Configure RSpec # Configure RSpec
RSpec.configure do |c| RSpec.configure do |c|
c.treat_symbols_as_metadata_keys_with_true_values = true c.treat_symbols_as_metadata_keys_with_true_values = true
@ -36,11 +40,15 @@ RSpec.configure do |c|
else else
c.filter_run_excluding :windows c.filter_run_excluding :windows
end end
c.after(:suite) do
FileUtils.rm_rf(VAGRANT_TEST_CWD)
end
end end
# Configure VAGRANT_CWD so that the tests never find an actual # Configure VAGRANT_CWD so that the tests never find an actual
# Vagrantfile anywhere, or at least this minimizes those chances. # Vagrantfile anywhere, or at least this minimizes those chances.
ENV["VAGRANT_CWD"] = Dir.mktmpdir("vagrant") ENV["VAGRANT_CWD"] = VAGRANT_TEST_CWD
# Set the dummy provider to the default for tests # Set the dummy provider to the default for tests
ENV["VAGRANT_DEFAULT_PROVIDER"] = "dummy" ENV["VAGRANT_DEFAULT_PROVIDER"] = "dummy"

View File

@ -35,7 +35,9 @@ describe VagrantPlugins::CommandBox::Command::Update do
context "updating specific box" do context "updating specific box" do
let(:argv) { ["--box", "foo"] } let(:argv) { ["--box", "foo"] }
let(:metadata_url) { Pathname.new(Dir.mktmpdir).join("metadata.json") } let(:scratch) { Dir.mktmpdir("vagrant-test-command-box-update-execute") }
let(:metadata_url) { Pathname.new(scratch).join("metadata.json") }
before do before do
metadata_url.open("w") do |f| metadata_url.open("w") do |f|
@ -46,6 +48,10 @@ describe VagrantPlugins::CommandBox::Command::Update do
"foo", "1.0", :virtualbox, metadata_url: metadata_url.to_s) "foo", "1.0", :virtualbox, metadata_url: metadata_url.to_s)
end end
after do
FileUtils.rm_rf(scratch)
end
it "doesn't update if they're up to date" do it "doesn't update if they're up to date" do
called = false called = false
allow(action_runner).to receive(:run) do |callable, opts| allow(action_runner).to receive(:run) do |callable, opts|

View File

@ -0,0 +1,37 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestArch::Cap::ChangeHostName" do
let(:described_class) do
VagrantPlugins::GuestArch::Plugin
.components
.guest_capabilities[:arch]
.get(:change_host_name)
end
let(:machine) { double("machine") }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
describe ".change_host_name" do
let(:hostname) { "example.com" }
it "sets the hostname" do
communicator.stub_command("sudo hostname | grep '#{hostname}'", exit_code: 1)
communicator.expect_command("hostnamectl set-hostname #{hostname}")
described_class.change_host_name(machine, hostname)
end
it "does not change the hostname if already set" do
communicator.stub_command("sudo hostname | grep '#{hostname}'", exit_code: 0)
described_class.change_host_name(machine, hostname)
expect(communicator.received_commands.size).to eq(1)
end
end
end

View File

@ -0,0 +1,48 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestArch::Cap::ConfigureNetworks" do
let(:described_class) do
VagrantPlugins::GuestArch::Plugin
.components
.guest_capabilities[:arch]
.get(:configure_networks)
end
let(:machine) { double("machine") }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
communicator.stub_command("ip -o -0 addr | grep -v LOOPBACK | awk '{print $2}' | sed 's/://'",
stdout: "eth1\neth2")
end
after do
communicator.verify_expectations!
end
describe ".configure_networks" do
let(:network_1) do
{
interface: 0,
type: "dhcp",
}
end
let(:network_2) do
{
interface: 1,
type: "static",
ip: "33.33.33.10",
netmask: "255.255.0.0",
gateway: "33.33.0.1",
}
end
it "creates and starts the networks" do
communicator.expect_command("ip link set eth1 down && netctl restart eth1 && netctl enable eth1")
communicator.expect_command("ip link set eth2 down && netctl restart eth2 && netctl enable eth2")
described_class.configure_networks(machine, [network_1, network_2])
end
end
end

View File

@ -0,0 +1,37 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestCoreOS::Cap::ChangeHostName" do
let(:described_class) do
VagrantPlugins::GuestCoreOS::Plugin
.components
.guest_capabilities[:coreos]
.get(:change_host_name)
end
let(:machine) { double("machine") }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
describe ".change_host_name" do
let(:hostname) { "example.com" }
it "sets the hostname" do
communicator.stub_command("sudo hostname --fqdn | grep '#{hostname}'", exit_code: 1)
communicator.expect_command("hostname example")
described_class.change_host_name(machine, hostname)
end
it "does not change the hostname if already set" do
communicator.stub_command("sudo hostname --fqdn | grep '#{hostname}'", exit_code: 0)
described_class.change_host_name(machine, hostname)
expect(communicator.received_commands.size).to eq(1)
end
end
end

View File

@ -1,10 +1,14 @@
require File.expand_path("../../../../../base", __FILE__) require_relative "../../../../base"
require File.expand_path("../../../support/shared/debian_like_host_name_examples", __FILE__) require_relative "../../support/shared/debian_like_host_name_examples"
describe "VagrantPlugins::GuestDebian::Cap::ChangeHostName" do describe "VagrantPlugins::GuestDebian::Cap::ChangeHostName" do
let(:described_class) do let(:described_class) do
VagrantPlugins::GuestDebian::Plugin.components.guest_capabilities[:debian].get(:change_host_name) VagrantPlugins::GuestDebian::Plugin
.components
.guest_capabilities[:debian]
.get(:change_host_name)
end end
let(:machine) { double("machine") } let(:machine) { double("machine") }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) } let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
let(:old_hostname) { 'oldhostname.olddomain.tld' } let(:old_hostname) { 'oldhostname.olddomain.tld' }

View File

@ -0,0 +1,50 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestDebian::Cap::ConfigureNetworks" do
let(:described_class) do
VagrantPlugins::GuestDebian::Plugin
.components
.guest_capabilities[:debian]
.get(:configure_networks)
end
let(:machine) { double("machine") }
let(:communicator) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(communicator)
end
after do
communicator.verify_expectations!
end
describe ".configure_networks" do
let(:network_0) do
{
interface: 0,
type: "dhcp",
}
end
let(:network_1) do
{
interface: 1,
type: "static",
ip: "33.33.33.10",
netmask: "255.255.0.0",
gateway: "33.33.0.1",
}
end
it "creates and starts the networks" do
communicator.expect_command("/sbin/ifdown eth0 2> /dev/null || true")
communicator.expect_command("/sbin/ip addr flush dev eth0 2> /dev/null")
communicator.expect_command("/sbin/ifdown eth1 2> /dev/null || true")
communicator.expect_command("/sbin/ip addr flush dev eth1 2> /dev/null")
communicator.expect_command("/sbin/ifup eth0")
communicator.expect_command("/sbin/ifup eth1")
described_class.configure_networks(machine, [network_0, network_1])
end
end
end

View File

@ -10,13 +10,17 @@ describe VagrantPlugins::DockerProvider::Config do
let(:machine) { double("machine") } let(:machine) { double("machine") }
let(:build_dir) do let(:build_dir) do
temporary_dir.tap do |dir| Dir.mktmpdir("vagrant-test-docker-provider-build-dir").tap do |dir|
dir.join("Dockerfile").open("w") do |f| File.open(File.join(dir, "Dockerfile"), "wb+") do |f|
f.write("Hello") f.write("Hello")
end end
end end
end end
after do
FileUtils.rm_rf(build_dir)
end
def assert_invalid def assert_invalid
errors = subject.validate(machine) errors = subject.validate(machine)
if !errors.values.any? { |v| !v.empty? } if !errors.values.any? { |v| !v.empty? }

View File

@ -125,6 +125,14 @@ describe VagrantPlugins::AtlasPush::Push do
end end
describe "#uploader_path" do describe "#uploader_path" do
let(:scratch) do
Pathname.new(Dir.mktmpdir("vagrant-test-atlas-push-upload-path"))
end
after do
FileUtils.rm_rf(scratch)
end
it "should return the configured path if set" do it "should return the configured path if set" do
config.uploader_path = "foo" config.uploader_path = "foo"
expect(subject.uploader_path).to eq("foo") expect(subject.uploader_path).to eq("foo")
@ -141,12 +149,10 @@ describe VagrantPlugins::AtlasPush::Push do
end end
it "should look up the uploader in the embedded dir if installer" do it "should look up the uploader in the embedded dir if installer" do
dir = temporary_dir
allow(Vagrant).to receive(:in_installer?).and_return(true) allow(Vagrant).to receive(:in_installer?).and_return(true)
allow(Vagrant).to receive(:installer_embedded_dir).and_return(dir.to_s) allow(Vagrant).to receive(:installer_embedded_dir).and_return(scratch.to_s)
bin_path = dir.join("bin", bin) bin_path = scratch.join("bin", bin)
bin_path.dirname.mkpath bin_path.dirname.mkpath
bin_path.open("w+") { |f| f.write("hi") } bin_path.open("w+") { |f| f.write("hi") }
@ -154,10 +160,8 @@ describe VagrantPlugins::AtlasPush::Push do
end end
it "should look up the uploader in the PATH if not in the installer" do it "should look up the uploader in the PATH if not in the installer" do
dir = temporary_dir
allow(Vagrant).to receive(:in_installer?).and_return(true) allow(Vagrant).to receive(:in_installer?).and_return(true)
allow(Vagrant).to receive(:installer_embedded_dir).and_return(dir.to_s) allow(Vagrant).to receive(:installer_embedded_dir).and_return(scratch.to_s)
expect(Vagrant::Util::Which).to receive(:which). expect(Vagrant::Util::Which).to receive(:which).
with(described_class.const_get(:UPLOADER_BIN)). with(described_class.const_get(:UPLOADER_BIN)).

View File

@ -64,7 +64,7 @@ describe VagrantPlugins::FTPPush::FTPAdapter do
describe "#upload" do describe "#upload" do
before do before do
@dir = Dir.mktmpdir @dir = Dir.mktmpdir("vagrant-ftp-push-adapter-upload")
FileUtils.touch("#{@dir}/file") FileUtils.touch("#{@dir}/file")
end end

View File

@ -41,7 +41,7 @@ describe VagrantPlugins::FTPPush::Push do
end end
@server.start @server.start
@dir = temporary_dir @dir = Dir.mktmpdir("vagrant-ftp-push")
FileUtils.touch("#{@dir}/.hidden.rb") FileUtils.touch("#{@dir}/.hidden.rb")
FileUtils.touch("#{@dir}/application.rb") FileUtils.touch("#{@dir}/application.rb")
FileUtils.touch("#{@dir}/config.rb") FileUtils.touch("#{@dir}/config.rb")
@ -51,6 +51,7 @@ describe VagrantPlugins::FTPPush::Push do
end end
after(:all) do after(:all) do
FileUtils.rm_rf(@dir)
@server.stop @server.stop
end end
@ -109,7 +110,7 @@ describe VagrantPlugins::FTPPush::Push do
describe "#all_files" do describe "#all_files" do
before(:all) do before(:all) do
@dir = Dir.mktmpdir @dir = Dir.mktmpdir("vagrant-ftp-push-push-all-files")
FileUtils.touch("#{@dir}/.hidden.rb") FileUtils.touch("#{@dir}/.hidden.rb")
FileUtils.touch("#{@dir}/application.rb") FileUtils.touch("#{@dir}/application.rb")
@ -151,9 +152,9 @@ describe VagrantPlugins::FTPPush::Push do
end end
end end
describe "includes_files" do describe "#includes_files" do
before(:all) do before(:all) do
@dir = Dir.mktmpdir @dir = Dir.mktmpdir("vagrant-ftp-push-includes-files")
FileUtils.touch("#{@dir}/.hidden.rb") FileUtils.touch("#{@dir}/.hidden.rb")
FileUtils.touch("#{@dir}/application.rb") FileUtils.touch("#{@dir}/application.rb")

View File

@ -132,8 +132,8 @@ module Unit
# @return [Pathname] Path to the newly created box. # @return [Pathname] Path to the newly created box.
def box1_file def box1_file
# Create a temporary directory to store our data we will tar up # Create a temporary directory to store our data we will tar up
td_source = Dir.mktmpdir td_source = Dir.mktmpdir("vagrant-box1-source")
td_dest = Dir.mktmpdir td_dest = Dir.mktmpdir("vagrant-box-1-dest")
# Store the temporary directory so it is not deleted until # Store the temporary directory so it is not deleted until
# this instance is garbage collected. # this instance is garbage collected.
@ -177,8 +177,8 @@ module Unit
}.merge(options[:metadata] || {}) }.merge(options[:metadata] || {})
# Create a temporary directory to store our data we will tar up # Create a temporary directory to store our data we will tar up
td_source = Dir.mktmpdir td_source = Dir.mktmpdir("vagrant-box-2-source")
td_dest = Dir.mktmpdir td_dest = Dir.mktmpdir("vagrant-box-2-dest")
# Store the temporary directory so it is not deleted until # Store the temporary directory so it is not deleted until
# this instance is garbage collected. # this instance is garbage collected.

View File

@ -73,19 +73,27 @@ shared_context "unit" do
end end
# This creates a temporary directory and returns a {Pathname} # This creates a temporary directory and returns a {Pathname}
# pointing to it. # pointing to it. If a block is given, the pathname is yielded and the
# temporary directory is removed at the end of the block.
# #
# @return [Pathname] # @return [Pathname]
def temporary_dir def temporary_dir
# Create a temporary directory and append it to the instance # Create a temporary directory and append it to the instance
# variabe so that it isn't garbage collected and deleted # variabe so that it isn't garbage collected and deleted
d = Dir.mktmpdir("vagrant") d = Dir.mktmpdir("vagrant-temporary-dir")
@_temp_files ||= [] @_temp_files ||= []
@_temp_files << d @_temp_files << d
# Return the pathname # Return the pathname
result = Pathname.new(Vagrant::Util::Platform.fs_real_path(d)) result = Pathname.new(Vagrant::Util::Platform.fs_real_path(d))
yield result if block_given? if block_given?
begin
yield result
ensure
FileUtils.rm_rf(result)
end
end
return result return result
end end

View File

@ -17,7 +17,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
let(:env) { { let(:env) { {
box_collection: box_collection, box_collection: box_collection,
hook: Proc.new { |name, env| env }, hook: Proc.new { |name, env| env },
tmp_path: Pathname.new(Dir.mktmpdir), tmp_path: Pathname.new(Dir.mktmpdir("vagrant-test-builtin-box-add")),
ui: Vagrant::UI::Silent.new, ui: Vagrant::UI::Silent.new,
} } } }
@ -31,6 +31,10 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
Vagrant::Box.new("foo", :virtualbox, "1.0", box_dir) Vagrant::Box.new("foo", :virtualbox, "1.0", box_dir)
end end
after do
FileUtils.rm_rf(env[:tmp_path])
end
# Helper to quickly SHA1 checksum a path # Helper to quickly SHA1 checksum a path
def checksum(path) def checksum(path)
FileChecksum.new(path, Digest::SHA1).checksum FileChecksum.new(path, Digest::SHA1).checksum
@ -39,9 +43,6 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
def with_ftp_server(path, **opts) def with_ftp_server(path, **opts)
path = Pathname.new(path) path = Pathname.new(path)
tf = Tempfile.new("vagrant")
tf.close
port = nil port = nil
server = nil server = nil
with_random_port do |port1, port2| with_random_port do |port1, port2|
@ -56,7 +57,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
end end
def with_web_server(path, **opts) def with_web_server(path, **opts)
tf = Tempfile.new("vagrant") tf = Tempfile.new("vagrant-web-server")
tf.close tf.close
opts[:json_type] ||= "application/json" opts[:json_type] ||= "application/json"
@ -74,6 +75,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
thr = Thread.new { server.start } thr = Thread.new { server.start }
yield port yield port
ensure ensure
tf.unlink
server.shutdown rescue nil server.shutdown rescue nil
thr.join rescue nil thr.join rescue nil
end end
@ -282,7 +284,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
context "with box metadata" do context "with box metadata" do
it "adds from HTTP URL" do it "adds from HTTP URL" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new(["vagrant", ".json"]).tap do |f| tf = Tempfile.new(["vagrant-test-box-http-url", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -325,7 +327,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds from HTTP URL with complex JSON mime type" do it "adds from HTTP URL with complex JSON mime type" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new(["vagrant", ".json"]).tap do |f| tf = Tempfile.new(["vagrant-test-http-json", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -370,7 +372,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds from shorthand path" do it "adds from shorthand path" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
td = Pathname.new(Dir.mktmpdir) td = Pathname.new(Dir.mktmpdir("vagrant-test-box-add-shorthand-path"))
tf = td.join("mitchellh", "precise64.json") tf = td.join("mitchellh", "precise64.json")
tf.dirname.mkpath tf.dirname.mkpath
tf.open("w") do |f| tf.open("w") do |f|
@ -414,11 +416,13 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
subject.call(env) subject.call(env)
end end
end end
FileUtils.rm_rf(td)
end end
it "add from shorthand path with configured server url" do it "add from shorthand path with configured server url" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
td = Pathname.new(Dir.mktmpdir) td = Pathname.new(Dir.mktmpdir("vagrant-test-box-add-server-url"))
tf = td.join("mitchellh", "precise64.json") tf = td.join("mitchellh", "precise64.json")
tf.dirname.mkpath tf.dirname.mkpath
tf.open("w") do |f| tf.open("w") do |f|
@ -461,11 +465,13 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
subject.call(env) subject.call(env)
end end
FileUtils.rm_rf(td)
end end
it "authenticates HTTP URLs and adds them" do it "authenticates HTTP URLs and adds them" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new(["vagrant", ".json"]).tap do |f| tf = Tempfile.new(["vagrant-test-http", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -523,7 +529,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds from HTTP URL with a checksum" do it "adds from HTTP URL with a checksum" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new(["vagrant", ".json"]).tap do |f| tf = Tempfile.new(["vagrant-test-http-checksum", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -568,7 +574,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "raises an exception if checksum given but not correct" do it "raises an exception if checksum given but not correct" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new(["vagrant", ".json"]).tap do |f| tf = Tempfile.new(["vagrant-test-bad-checksum", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -606,9 +612,6 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
end end
it "raises an error if no Vagrant server is set" do it "raises an error if no Vagrant server is set" do
tf = Tempfile.new("foo")
tf.close
env[:box_url] = "mitchellh/precise64.json" env[:box_url] = "mitchellh/precise64.json"
expect(box_collection).to receive(:add).never expect(box_collection).to receive(:add).never
@ -621,10 +624,9 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
end end
it "raises an error if shorthand is invalid" do it "raises an error if shorthand is invalid" do
tf = Tempfile.new("foo") path = Dir::Tmpname.create("vagrant-shorthand-invalid") {}
tf.close
with_web_server(Pathname.new(tf.path)) do |port| with_web_server(Pathname.new(path)) do |port|
env[:box_url] = "mitchellh/precise64.json" env[:box_url] = "mitchellh/precise64.json"
expect(box_collection).to receive(:add).never expect(box_collection).to receive(:add).never
@ -640,7 +642,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "raises an error if multiple metadata URLs are given" do it "raises an error if multiple metadata URLs are given" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-multi-metadata", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -676,7 +678,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the latest version of a box with only one provider" do it "adds the latest version of a box with only one provider" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-latest-version", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -715,7 +717,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the latest version of a box with the specified provider" do it "adds the latest version of a box with the specified provider" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-specific-provider", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -761,7 +763,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the latest version of a box with the specified provider, even if not latest" do it "adds the latest version of a box with the specified provider, even if not latest" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-specified-provider", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -810,7 +812,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the constrained version of a box with the only provider" do it "adds the constrained version of a box with the only provider" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-constrained", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -850,7 +852,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the constrained version of a box with the specified provider" do it "adds the constrained version of a box with the specified provider" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-constrained-provider", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -895,7 +897,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "adds the latest version of a box with any specified provider" do it "adds the latest version of a box with any specified provider" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-latest-version", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -943,7 +945,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "asks the user what provider if multiple options" do it "asks the user what provider if multiple options" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-provider-asks", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -989,7 +991,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "raises an exception if the name doesn't match a requested name" do it "raises an exception if the name doesn't match a requested name" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-name-mismatch", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -1024,7 +1026,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "raises an exception if no matching version" do it "raises an exception if no matching version" do
box_path = iso_env.box2_file(:vmware) box_path = iso_env.box2_file(:vmware)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-no-matching-version", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -1055,7 +1057,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
end end
it "raises an error if there is no matching provider" do it "raises an error if there is no matching provider" do
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-no-matching-provider", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -1089,7 +1091,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "raises an error if a box already exists" do it "raises an error if a box already exists" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-already-exists", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",
@ -1124,7 +1126,7 @@ describe Vagrant::Action::Builtin::BoxAdd, :skip_windows do
it "force adds a box if specified" do it "force adds a box if specified" do
box_path = iso_env.box2_file(:virtualbox) box_path = iso_env.box2_file(:virtualbox)
tf = Tempfile.new("vagrant").tap do |f| tf = Tempfile.new(["vagrant-box-force-add", ".json"]).tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo/bar", "name": "foo/bar",

View File

@ -4,8 +4,7 @@ describe Vagrant::Action::Builtin::Lock do
let(:app) { lambda { |env| } } let(:app) { lambda { |env| } }
let(:env) { {} } let(:env) { {} }
let(:lock_path) do let(:lock_path) do
@__lock_path = Tempfile.new("vagrant-test-lock") Dir::Tmpname.create("vagrant-test-lock") {}
@__lock_path.path.to_s
end end
let(:options) do let(:options) do
@ -15,6 +14,10 @@ describe Vagrant::Action::Builtin::Lock do
} }
end end
after do
File.unlink(lock_path) if File.file?(lock_path)
end
it "should require a path" do it "should require a path" do
expect { described_class.new(app, env) }. expect { described_class.new(app, env) }.
to raise_error(ArgumentError) to raise_error(ArgumentError)

View File

@ -13,9 +13,9 @@ describe Vagrant::Action::Builtin::MixinSyncedFolders do
end end
end end
let(:machine) do let(:data_dir) { Pathname.new(Dir.mktmpdir("vagrant-test-mixin-synced-folders")) }
data_dir = Pathname.new(Dir.mktmpdir)
let(:machine) do
double("machine").tap do |machine| double("machine").tap do |machine|
allow(machine).to receive(:config).and_return(machine_config) allow(machine).to receive(:config).and_return(machine_config)
allow(machine).to receive(:data_dir).and_return(data_dir) allow(machine).to receive(:data_dir).and_return(data_dir)
@ -30,6 +30,10 @@ describe Vagrant::Action::Builtin::MixinSyncedFolders do
let(:vm_config) { double("machine_vm_config", :allowed_synced_folder_types => nil) } let(:vm_config) { double("machine_vm_config", :allowed_synced_folder_types => nil) }
after do
FileUtils.rm_rf(data_dir)
end
describe "default_synced_folder_type" do describe "default_synced_folder_type" do
it "returns the usable implementation" do it "returns the usable implementation" do
plugins = { plugins = {

View File

@ -53,12 +53,16 @@ describe Vagrant::Action::Builtin::SyncedFolderCleanup do
plugins[:nfs] = [impl(true, "nfs"), 5] plugins[:nfs] = [impl(true, "nfs"), 5]
env[:machine] = Object.new env[:machine] = Object.new
env[:root_path] = Pathname.new(Dir.mktmpdir) env[:root_path] = Pathname.new(Dir.mktmpdir("vagrant-test-synced-folder-cleanup-call"))
subject.stub(plugins: plugins) subject.stub(plugins: plugins)
subject.stub(synced_folders: synced_folders) subject.stub(synced_folders: synced_folders)
end end
after do
FileUtils.rm_rf(env[:root_path])
end
it "should invoke cleanup" do it "should invoke cleanup" do
tracker = create_cleanup_tracker tracker = create_cleanup_tracker
plugins[:tracker] = [tracker, 15] plugins[:tracker] = [tracker, 15]

View File

@ -41,12 +41,16 @@ describe Vagrant::Action::Builtin::SyncedFolders do
plugins[:default] = [impl(true, "default"), 10] plugins[:default] = [impl(true, "default"), 10]
plugins[:nfs] = [impl(true, "nfs"), 5] plugins[:nfs] = [impl(true, "nfs"), 5]
env[:root_path] = Pathname.new(Dir.mktmpdir) env[:root_path] = Pathname.new(Dir.mktmpdir("vagrant-test-synced-folders-call"))
subject.stub(plugins: plugins) subject.stub(plugins: plugins)
subject.stub(synced_folders: synced_folders) subject.stub(synced_folders: synced_folders)
allow(subject).to receive(:save_synced_folders) allow(subject).to receive(:save_synced_folders)
end end
after do
FileUtils.rm_rf(env[:root_path])
end
it "should create on the host if specified" do it "should create on the host if specified" do
synced_folders["default"] = { synced_folders["default"] = {
"root" => { "root" => {

View File

@ -39,8 +39,13 @@ describe Vagrant::BoxCollection, :skip_windows do
end end
it 'does not raise an exception when a file appears in the boxes dir' do it 'does not raise an exception when a file appears in the boxes dir' do
Tempfile.new('a_file', environment.boxes_dir) t = Tempfile.new('a_file', environment.boxes_dir)
expect { subject.all }.to_not raise_error t.close
begin
expect { subject.all }.to_not raise_error
ensure
t.unlink
end
end end
end end

View File

@ -227,7 +227,7 @@ describe Vagrant::Box, :skip_windows do
context "#load_metadata" do context "#load_metadata" do
let(:metadata_url) do let(:metadata_url) do
Tempfile.new("vagrant").tap do |f| Tempfile.new("vagrant-test-box-test").tap do |f|
f.write(<<-RAW) f.write(<<-RAW)
{ {
"name": "foo", "name": "foo",
@ -244,6 +244,10 @@ describe Vagrant::Box, :skip_windows do
metadata_url: metadata_url.path) metadata_url: metadata_url.path)
end end
after do
metadata_url.unlink
end
it "loads the url and returns the data" do it "loads the url and returns the data" do
result = subject.load_metadata result = subject.load_metadata
expect(result.name).to eq("foo") expect(result.name).to eq("foo")
@ -286,6 +290,14 @@ describe Vagrant::Box, :skip_windows do
end end
describe "repackaging" do describe "repackaging" do
let(:scratch) { Dir.mktmpdir("vagrant-test-box-repackaging") }
let(:box_output_path) { File.join(scratch, "package.box") }
after do
FileUtils.rm_rf(scratch)
end
it "should repackage the box" do it "should repackage the box" do
test_file_contents = "hello, world!" test_file_contents = "hello, world!"
@ -296,7 +308,6 @@ describe Vagrant::Box, :skip_windows do
end end
# Repackage our box to some temporary directory # Repackage our box to some temporary directory
box_output_path = temporary_dir.join("package.box")
expect(subject.repackage(box_output_path)).to be_true expect(subject.repackage(box_output_path)).to be_true
# Let's now add this box again under a different name, and then # Let's now add this box again under a different name, and then

View File

@ -69,14 +69,14 @@ describe Vagrant::Environment do
describe "#home_path" do describe "#home_path" do
it "is set to the home path given" do it "is set to the home path given" do
temporary_dir do |dir| Dir.mktmpdir("vagrant-test-env-home-path-given") do |dir|
instance = described_class.new(home_path: dir) instance = described_class.new(home_path: dir)
expect(instance.home_path).to eq(Pathname.new(dir)) expect(instance.home_path).to eq(Pathname.new(dir))
end end
end end
it "is set to the environmental variable VAGRANT_HOME" do it "is set to the environmental variable VAGRANT_HOME" do
temporary_dir do |dir| Dir.mktmpdir("vagrant-test-env-home-env-var") do |dir|
instance = with_temp_env("VAGRANT_HOME" => dir.to_s) do instance = with_temp_env("VAGRANT_HOME" => dir.to_s) do
described_class.new described_class.new
end end
@ -99,7 +99,7 @@ describe Vagrant::Environment do
end end
it "is okay if it has the current version" do it "is okay if it has the current version" do
Dir.mktmpdir do |dir| Dir.mktmpdir("vagrant-test-env-current-version") do |dir|
Pathname.new(dir).join("setup_version").open("w") do |f| Pathname.new(dir).join("setup_version").open("w") do |f|
f.write(Vagrant::Environment::CURRENT_SETUP_VERSION) f.write(Vagrant::Environment::CURRENT_SETUP_VERSION)
end end
@ -112,7 +112,7 @@ describe Vagrant::Environment do
end end
it "raises an exception if the version is newer than ours" do it "raises an exception if the version is newer than ours" do
Dir.mktmpdir do |dir| Dir.mktmpdir("vagrant-test-env-newer-version") do |dir|
Pathname.new(dir).join("setup_version").open("w") do |f| Pathname.new(dir).join("setup_version").open("w") do |f|
f.write("100.5") f.write("100.5")
end end
@ -123,7 +123,7 @@ describe Vagrant::Environment do
end end
it "raises an exception if there is an unknown home directory version" do it "raises an exception if there is an unknown home directory version" do
Dir.mktmpdir do |dir| Dir.mktmpdir("vagrant-test-env-unknown-home") do |dir|
Pathname.new(dir).join("setup_version").open("w") do |f| Pathname.new(dir).join("setup_version").open("w") do |f|
f.write("0.7") f.write("0.7")
end end
@ -645,7 +645,7 @@ VF
describe "active machines" do describe "active machines" do
it "should be empty if there is no root path" do it "should be empty if there is no root path" do
Dir.mktmpdir do |temp_dir| Dir.mktmpdir("vagrant-test-env-no-root-path") do |temp_dir|
instance = described_class.new(cwd: temp_dir) instance = described_class.new(cwd: temp_dir)
expect(instance.active_machines).to be_empty expect(instance.active_machines).to be_empty
end end
@ -715,7 +715,7 @@ VF
describe "current working directory" do describe "current working directory" do
it "is the cwd by default" do it "is the cwd by default" do
Dir.mktmpdir do |temp_dir| Dir.mktmpdir("vagrant-test-env-cwd-default") do |temp_dir|
Dir.chdir(temp_dir) do Dir.chdir(temp_dir) do
with_temp_env("VAGRANT_CWD" => nil) do with_temp_env("VAGRANT_CWD" => nil) do
expect(described_class.new.cwd).to eq(Pathname.new(Dir.pwd)) expect(described_class.new.cwd).to eq(Pathname.new(Dir.pwd))
@ -725,14 +725,14 @@ VF
end end
it "is set to the cwd given" do it "is set to the cwd given" do
Dir.mktmpdir do |directory| Dir.mktmpdir("vagrant-test-env-set-cwd") do |directory|
instance = described_class.new(cwd: directory) instance = described_class.new(cwd: directory)
expect(instance.cwd).to eq(Pathname.new(directory)) expect(instance.cwd).to eq(Pathname.new(directory))
end end
end end
it "is set to the environmental variable VAGRANT_CWD" do it "is set to the environmental variable VAGRANT_CWD" do
Dir.mktmpdir do |directory| Dir.mktmpdir("vagrant-test-env-set-vagrant-cwd") do |directory|
instance = with_temp_env("VAGRANT_CWD" => directory) do instance = with_temp_env("VAGRANT_CWD" => directory) do
described_class.new described_class.new
end end
@ -905,7 +905,7 @@ VF
end end
it "is expanded relative to the cwd" do it "is expanded relative to the cwd" do
Dir.mktmpdir do |temp_dir| Dir.mktmpdir("vagrant-test-env-relative-cwd") do |temp_dir|
Dir.chdir(temp_dir) do Dir.chdir(temp_dir) do
instance = described_class.new(local_data_path: "foo") instance = described_class.new(local_data_path: "foo")
expect(instance.local_data_path).to eq(instance.cwd.join("foo")) expect(instance.local_data_path).to eq(instance.cwd.join("foo"))
@ -915,7 +915,7 @@ VF
end end
it "is set to the given value" do it "is set to the given value" do
Dir.mktmpdir do |dir| Dir.mktmpdir("vagrant-test-env-set-given") do |dir|
instance = described_class.new(local_data_path: dir) instance = described_class.new(local_data_path: dir)
expect(instance.local_data_path.to_s).to eq(dir) expect(instance.local_data_path.to_s).to eq(dir)
end end
@ -923,7 +923,7 @@ VF
describe "upgrading V1 dotfiles" do describe "upgrading V1 dotfiles" do
let(:v1_dotfile_tempfile) do let(:v1_dotfile_tempfile) do
Tempfile.new("vagrant").tap do |f| Tempfile.new("vagrant-upgrade-dotfile").tap do |f|
f.close f.close
end end
end end
@ -932,6 +932,10 @@ VF
let(:local_data_path) { v1_dotfile_tempfile.path } let(:local_data_path) { v1_dotfile_tempfile.path }
let(:instance) { described_class.new(local_data_path: local_data_path) } let(:instance) { described_class.new(local_data_path: local_data_path) }
after do
FileUtils.rm_rf(local_data_path)
end
it "should be fine if dotfile is empty" do it "should be fine if dotfile is empty" do
v1_dotfile.open("w+") do |f| v1_dotfile.open("w+") do |f|
f.write("") f.write("")

View File

@ -9,7 +9,7 @@ require "vagrant/machine_index"
describe Vagrant::MachineIndex do describe Vagrant::MachineIndex do
include_context "unit" include_context "unit"
let(:data_dir) { temporary_dir } let(:data_dir) { Pathname.new(Dir.mktmpdir("vagrant-test-machine-index-data-dir")) }
let(:entry_klass) { Vagrant::MachineIndex::Entry } let(:entry_klass) { Vagrant::MachineIndex::Entry }
let(:new_entry) do let(:new_entry) do
@ -21,6 +21,10 @@ describe Vagrant::MachineIndex do
subject { described_class.new(data_dir) } subject { described_class.new(data_dir) }
after do
FileUtils.rm_rf(data_dir)
end
it "raises an exception if the data file is corrupt" do it "raises an exception if the data file is corrupt" do
data_dir.join("index").open("w") do |f| data_dir.join("index").open("w") do |f|
f.write(JSON.dump({})) f.write(JSON.dump({}))

View File

@ -28,7 +28,7 @@ describe Vagrant::Machine do
end end
let(:config) { env.vagrantfile.config } let(:config) { env.vagrantfile.config }
let(:data_dir) { Pathname.new(Dir.mktmpdir("vagrant")) } let(:data_dir) { Pathname.new(Dir.mktmpdir("vagrant-machine-data-dir")) }
let(:env) do let(:env) do
# We need to create a Vagrantfile so that this test environment # We need to create a Vagrantfile so that this test environment
# has a proper root path # has a proper root path
@ -42,6 +42,10 @@ describe Vagrant::Machine do
let(:instance) { new_instance } let(:instance) { new_instance }
after do
FileUtils.rm_rf(data_dir) if data_dir
end
subject { instance } subject { instance }
def new_provider_mock def new_provider_mock

View File

@ -11,11 +11,7 @@ describe Vagrant::Plugin::Manager do
include_context "unit" include_context "unit"
let(:path) do let(:path) do
f = Tempfile.new("vagrant") Pathname.new(Dir::Tmpname.create("vagrant-test-plugin-manager") {})
p = f.path
f.close
f.unlink
Pathname.new(p)
end end
let(:bundler) { double("bundler") } let(:bundler) { double("bundler") }

View File

@ -5,11 +5,7 @@ require File.expand_path("../../../base", __FILE__)
describe Vagrant::Plugin::StateFile do describe Vagrant::Plugin::StateFile do
let(:path) do let(:path) do
f = Tempfile.new("vagrant") Pathname.new(Dir::Tmpname.create("vagrant-test-statefile") {})
p = f.path
f.close
f.unlink
Pathname.new(p)
end end
after do after do

View File

@ -5,10 +5,17 @@ require File.expand_path("../../../base", __FILE__)
require 'vagrant/util/safe_chdir' require 'vagrant/util/safe_chdir'
describe Vagrant::Util::SafeChdir do describe Vagrant::Util::SafeChdir do
let(:temp_dir) { Dir.mktmpdir("vagrant-test-util-safe-chdir") }
let(:temp_dir2) { Dir.mktmpdir("vagrant-test-util-safe-chdir-2") }
after do
FileUtils.rm_rf(temp_dir)
FileUtils.rm_rf(temp_dir2)
end
it "should change directories" do it "should change directories" do
expected = nil expected = nil
result = nil result = nil
temp_dir = Dir.mktmpdir
Dir.chdir(temp_dir) do Dir.chdir(temp_dir) do
expected = Dir.pwd expected = Dir.pwd
@ -24,15 +31,14 @@ describe Vagrant::Util::SafeChdir do
it "should allow recursive chdir" do it "should allow recursive chdir" do
expected = nil expected = nil
result = nil result = nil
temp_path = Dir.mktmpdir
Dir.chdir(temp_path) do Dir.chdir(temp_dir) do
expected = Dir.pwd expected = Dir.pwd
end end
expect do expect do
described_class.safe_chdir(Dir.mktmpdir) do described_class.safe_chdir(temp_dir2) do
described_class.safe_chdir(temp_path) do described_class.safe_chdir(temp_dir) do
result = Dir.pwd result = Dir.pwd
end end
end end

View File

@ -58,7 +58,7 @@ describe Vagrant::Vagrantfile do
describe "#machine" do describe "#machine" do
let(:boxes) { Vagrant::BoxCollection.new(iso_env.boxes_dir) } let(:boxes) { Vagrant::BoxCollection.new(iso_env.boxes_dir) }
let(:data_path) { Pathname.new(Dir.mktmpdir) } let(:data_path) { Pathname.new(Dir.mktmpdir("vagrant-machine-data-path")) }
let(:env) { iso_env.create_vagrant_env } let(:env) { iso_env.create_vagrant_env }
let(:iso_env) { isolated_environment } let(:iso_env) { isolated_environment }
let(:vagrantfile) { described_class.new(loader, keys) } let(:vagrantfile) { described_class.new(loader, keys) }
@ -86,6 +86,10 @@ describe Vagrant::Vagrantfile do
VF VF
end end
after do
FileUtils.rm_rf(data_path.to_s)
end
describe '#data_dir' do describe '#data_dir' do
subject { super().data_dir } subject { super().data_dir }
it { should eq(data_path) } it { should eq(data_path) }