Permalink
Browse files

fix "invalid byte sequence in UTF-8" error when decoding files

add necessary tests
remove force_encoding from File#bdecode
  • Loading branch information...
1 parent dbf7436 commit d00e6720e4a96c9cc0301d09c30d2f0dafd3087d quaternion committed Mar 23, 2012
Showing with 55 additions and 28 deletions.
  1. +6 −6 lib/bencodr/io.rb
  2. +49 −22 spec/bencodr/io_spec.rb
View
@@ -6,22 +6,22 @@ module ClassMethods
def bencode(fd, object)
open(fd, "wb") {|file| file.bencode(object)}
end
-
+
def bdecode(fd)
open(fd, "rb") {|file| file.bdecode}
end
end
-
+
def bencode(object)
write(Object.bencode(object))
end
-
+
def bdecode
- Object.bdecode(read.force_encoding('UTF-8'))
+ Object.bdecode(read)
end
-
+
def self.included(base)
base.extend ClassMethods
end
end
-end
+end
View
@@ -1,35 +1,62 @@
# encoding: UTF-8
require "spec_helper"
+require 'tempfile'
describe File do
before :all do
- @path = "tmp"
- Dir.mkdir(@path) unless File.exists? @path
BEncodr.include!
end
- before :each do
- @file = File.join(@path, 'test.bencodr')
- @object = "string"
- File.bencode(@file, @object)
+ let(:file) { Tempfile.new('test.bencodr') }
+ let(:object) { "string" }
+
+ describe ".bencode" do
+ it "should encode object to file" do
+ File.bencode(file, object)
+ file.rewind
+ file.read.should == "6:string"
+ end
end
-
+
describe "#bencode" do
- subject{ File }
-
- it{ File.should exist(@file) }
- end
-
- describe "#bdecode" do
- subject{ File }
- it{ should bdecode(@file).to(@object) }
- end
-
- after :each do
- File.delete(@file)
+ it "should encode object to file" do
+ file.bencode(object)
+ file.rewind
+ file.read.should == "6:string"
+ end
end
- after :all do
- Dir.delete(@path) if File.exists? @path
+ context "decode" do
+ let(:sample_path) { 'spec/samples/bencodr.torrent' }
+
+ before do
+ file.bencode(object)
+ file.rewind
+ end
+
+ describe ".bdecode" do
+ subject{ File }
+
+ it "should decode object from file" do
+ should bdecode(file).to(object)
+ end
+
+ it "should decode sample file without error" do
+ expect{ File.bdecode(sample_path) }.to_not raise_error
+ end
+ end
+
+ describe "#bdecode" do
+ subject{ file }
+
+ it "should decode object from file" do
+ should bdecode_to(object)
+ end
+
+ it "should decode sample file without error" do
+ f = File.open(sample_path, 'rb')
+ expect{ f.bdecode }.to_not raise_error
+ end
+ end
end
-end
+end

0 comments on commit d00e672

Please sign in to comment.