Created
October 1, 2012 16:01
-
-
Save gavinandresen/3812689 to your computer and use it in GitHub Desktop.
Testing tool: corrupt a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python -u | |
# Read from stdin, corrupt/remove random bytes, write to standard out. | |
import optparse | |
import random | |
import sys | |
def main(): | |
parser = optparse.OptionParser(usage="%prog [options]") | |
parser.add_option("--n", dest="n", type="int", default=1, | |
help="how many single-byte errors to introduce") | |
parser.add_option("--r", dest="remove", type="int", default=0, | |
help="how many bytes to erase") | |
parser.add_option("--verbose", dest="verbose", action="store_true", | |
help="be verbose") | |
(options, args) = parser.parse_args() | |
data = bytearray(sys.stdin.read()) | |
for i in range(0, options.n): | |
position = random.randrange(0, len(data)) | |
oldbyte = data[position] | |
newbyte = (oldbyte+random.randrange(1,256))%256 | |
data[position] = newbyte | |
if options.verbose: | |
print >> sys.stderr, "Replaced byte %d with %d at position %d"%(oldbyte,newbyte,position) | |
for i in range(0, options.remove): | |
position = random.randrange(0, len(data)) | |
oldbyte = data[position] | |
del data[position] | |
if options.verbose: | |
print >> sys.stderr, "Deleted byte at position %d"%(position) | |
sys.stdout.write(data) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment