require 'spec_helper' require 'ronin/exploits/loot/file' require 'tmpdir' describe Ronin::Exploits::Loot::File do let(:path) { 'test.txt' } let(:contents) { 'this is a test' } subject { described_class.new(path,contents) } describe "#initialize" do it "must set #path" do expect(subject.path).to eq(path) end it "must set #contents" do expect(subject.contents).to eq(contents) end it "must default #format to nil" do expect(subject.format).to be(nil) end context "when given the format: keyword argument" do let(:format) { :json } subject { described_class.new(path,contents, format: format) } it "must set #format" do expect(subject.format).to be(format) end end end describe "#to_s" do context "when #format is nil" do it "must return the #contents" do expect(subject.contents).to eq(contents) end context "when #contents is not a String" do let(:contents) { 42 } it "must call #to_s on #contents" do expect(subject.to_s).to eq(contents.to_s) end end end context "when #format is :json" do let(:contents) do [true, 42, 1.0, [], {}] end let(:format) { :json } subject { described_class.new(path,contents, format: format) } it "must convert #contents to pretty JSON" do expect(subject.to_s).to eq(JSON.pretty_generate(contents)) end end context "when #format is :yaml" do let(:contents) do {foo: true, bar: {baz: 42}} end let(:format) { :yaml } subject { described_class.new(path,contents, format: format) } it "must convert #contents to YAML" do expect(subject.to_s).to eq(YAML.dump(contents)) end end context "when #format is :csv" do let(:contents) do [ %w[A B C ], %w[foo bar baz] ] end let(:format) { :csv } subject { described_class.new(path,contents, format: format) } it "must convert #contents to CSV" do expect(subject.to_s).to eq( contents.map(&:to_csv).join ) end end context "when #format is an unknown value" do let(:format) { :foo } subject { described_class.new(path,contents, format: format) } it do expect { subject.to_s }.to raise_error(NotImplementedError,"unsupported loot format: #{format.inspect}") end end end describe "#save" do let(:output_dir) { Dir.mktmpdir('ronin-exploits-loot') } before { subject.save(output_dir) } it "must write the #contents to the #path within the output directory" do expect(File.read(File.join(output_dir,path))).to eq(contents) end context "when the path is a multi-directory relative path" do let(:path) { 'path/to/test.txt' } it "must create the parent directories" do parent_dir = File.dirname(File.join(output_dir,path)) expect(File.directory?(parent_dir)).to be(true) end it "must write the #contents to the #path within the output directory" do expect(File.read(File.join(output_dir,path))).to eq(contents) end end end end