Unittest - testing for filenames and filesize
Hi.
I need help with an assignment and I hope you guys can guide me in the right
direction.
This is the code:
--
"""
Demostration of setUp and tearDown.
The tests do not actually test anything - this is a demo.
"""
import unittest
import tempfile
import shutil
import glob
import os
class FileTest(unittest.TestCase):
def setUp(self):
self.origdir = os.getcwd()
self.dirname = tempfile.mkdtemp("testdir")
os.chdir(self.dirname)
def test_1(self):
"Verify creation of files is possible"
for filename in ("this.txt", "that.txt", "the_other.txt"):
f = open(filename, "w")
f.write("Some text\n")
f.close()
self.assertTrue(f.closed)
def test_2(self):
"Verify that current directory is empty"
self.assertEqual(glob.glob("*"), [], "Directory not empty")
def tearDown(self):
os.chdir(self.origdir)
shutil.rmtree(self.dirname)
-
I need to modify this code as following:
1. The test_1() method includes code to verify that the test directory contains
only the files created by the for loop. Hint: You might create a set containing
the list of three filenames, and then create a set from the os.listdir() method.
2. A test_3() method creates a binary file that contains exactly a million
bytes, closes it and then uses os.stat to verify that the file on disk is of
the correct length (with os.stat, statinfo.st_size returns the size in bytes).
I'm new to Python programming so I don't know where to put the set in point 1.
Before the test or under test1.
Would appreciate pointers and solutions (with explanation)for both point 1 and
2.
Thank you in advance.
T
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unittest - testing for filenames and filesize
Thank you guys, Roy and Terry.
I has been great help.
I still need some help. Here is the updated code:
Demostration of setUp and tearDown.
The tests do not actually test anything - this is a demo.
"""
import unittest
import tempfile
import shutil
import glob
import os
class FileTest(unittest.TestCase):
def setUp(self):
self.origdir = os.getcwd()
self.dirname = tempfile.mkdtemp("testdir")
os.chdir(self.dirname)
def test_1(self):
"Verify creation of files is possible"
filenames = {"this.txt", "that.txt", "the_other.txt"}
for filename in filenames:
f = open(filename, "w")
f.write("Some text\n")
f.close()
self.assertTrue(f.closed)
dir_names = set(os.listdir('.'))
self.assertEqual(set(dir_names), set(filenames))
def test_2(self):
"Verify that current directory is empty"
self.assertEqual(glob.glob("*"), [], "Directory not empty")
def test_3(self):
f = open("test.dat", "wb")
filesize = b"0"*100
f.write(filesize)
f.close()
self.assertEqual(os.stat, filesize)
def tearDown(self):
os.chdir(self.origdir)
shutil.rmtree(self.dirname
The test_3 is to test if the created binary file har the size of 1 million
bytes. Somehow it is not working. Any suggestions?
Thanks
T
kl. 21:06:29 UTC+2 torsdag 23. august 2012 skrev Roy Smith følgende:
> On Thursday, August 23, 2012 1:29:19 PM UTC-4, Terry Reedy wrote:
>
>
>
> > One can start with a set rather than tuple of file names.
>
> > filenames = {"this.txt", "that.txt", "the_other.txt"}
>
>
>
> Yeah, that's even cleaner. Just be aware, the set notation above is only
> available in (IIRC), 2.7 or above.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unittest - testing for filenames and filesize
Thanks Rob,
I'v modified the test_3 like this:
def test_3(self):
f = open("test.dat", "wb")
filesize = (b'b'*100)
f.write(filesize)
f.close()
statinfo = os.stat("test.dat")
self.assertEqual(statinfo.st_size, filesize)
I'm still getting AssertionError and the error says: 100 !=b'
Help appreciated.
T
kl. 21:04:54 UTC+2 fredag 24. august 2012 skrev Robert Day følgende:
> On Fri, 2012-08-24 at 09:20 -0700, Tigerstyle wrote:
>
>
>
> > def test_3(self):
>
> > f = open("test.dat", "wb")
>
> > filesize = b"0"*100
>
> > f.write(filesize)
>
> > f.close()
>
> > self.assertEqual(os.stat, filesize)
>
>
>
> > The test_3 is to test if the created binary file har the size of 1 million
> > bytes. Somehow it is not working. Any suggestions?
>
> >
>
>
>
> rob@rivertam:~$ python
>
> Python 2.7.3 (default, Jul 24 2012, 10:05:38)
>
> [GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2
>
> Type "help", "copyright", "credits" or "license" for more information.
>
> >>> import os
>
> >>> os.stat
>
>
>
> >>>
>
>
>
> So that's what 'os.stat' is. Why are you testing whether that's equal to
>
> b"0"*100?
>
>
>
> (You may find the documentation on os.stat at
>
> http://docs.python.org/library/os.html#os.stat helpful; it's a function
>
> which takes a path as its argument, and returns an object with some
>
> relevant attributes.)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unittest - testing for filenames and filesize
Ahh, thank you very much Rob. Fixed now. Have a great day. T kl. 19:51:54 UTC+2 søndag 26. august 2012 skrev Rob Day følgende: > On Sun, 2012-08-26 at 10:36 -0700, Tigerstyle wrote: > > > self.assertEqual(statinfo.st_size, filesize) > > > > > > I'm still getting AssertionError and the error says: 100 !=b' > > > > > > > > > > filesize is the character 'b' repeated one million times (the contents > > of the file, in other words). statinfo.st_size is the number of bytes in > > the file, i.e. 1,000,000. So when your assertEqual code checks if those > > two values are equal, what do you think happens? -- http://mail.python.org/mailman/listinfo/python-list
Function for examine content of directory
Hi guys,
I'm trying to write a module containing a function to examine the contents of
the current working directory and print out a count of how many files have each
extension (".txt", ".doc", etc.)
This is the code so far:
--
import os
path = "v:\\workspace\\Python2_Homework03\\src\\"
dirs = os.listdir( path )
filenames = {"this.txt", "that.txt",
"the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
extensions = []
for filename in filenames:
f = open(filename, "w")
f.write("Some text\n")
f.close()
name , ext = os.path.splitext(f.name)
extensions.append(ext)
# This would print all the files and directories
for file in dirs:
print(file)
for ext in extensions:
print("Count for %s: " %ext, extensions.count(ext))
--
When I'm trying to get the module to print how many files each extension has,
it prints the count of each ext multiple times for each extension type. Like
this:
this.pdf
the_other.txt
this.doc
that.txt
this.txt
that.pdf
first.txt
that.doc
Count for .pdf: 2
Count for .txt: 4
Count for .doc: 2
Count for .txt: 4
Count for .txt: 4
Count for .pdf: 2
Count for .txt: 4
Count for .doc: 2
Any help is appreciated.
T
--
http://mail.python.org/mailman/listinfo/python-list
Re: Function for examine content of directory
Thanks, just what I was looking for :-)
T
kl. 17:20:27 UTC+2 torsdag 6. september 2012 skrev MRAB følgende:
> On 06/09/2012 15:56, Tigerstyle wrote:
>
> > Hi guys,
>
> >
>
> > I'm trying to write a module containing a function to examine the contents
> > of the current working directory and print out a count of how many files
> > have each extension (".txt", ".doc", etc.)
>
> >
>
> > This is the code so far:
>
> > --
>
> > import os
>
> >
>
> > path = "v:\\workspace\\Python2_Homework03\\src\\"
>
> > dirs = os.listdir( path )
>
> > filenames = {"this.txt", "that.txt",
> > "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
>
> > extensions = []
>
> > for filename in filenames:
>
> > f = open(filename, "w")
>
> > f.write("Some text\n")
>
> > f.close()
>
> > name , ext = os.path.splitext(f.name)
>
> > extensions.append(ext)
>
> >
>
> > # This would print all the files and directories
>
> > for file in dirs:
>
> > print(file)
>
> >
>
> > for ext in extensions:
>
> > print("Count for %s: " %ext, extensions.count(ext))
>
> >
>
> > --
>
> >
>
> > When I'm trying to get the module to print how many files each extension
> > has, it prints the count of each ext multiple times for each extension
> > type. Like this:
>
> >
>
> > this.pdf
>
> > the_other.txt
>
> > this.doc
>
> > that.txt
>
> > this.txt
>
> > that.pdf
>
> > first.txt
>
> > that.doc
>
> > Count for .pdf: 2
>
> > Count for .txt: 4
>
> > Count for .doc: 2
>
> > Count for .txt: 4
>
> > Count for .txt: 4
>
> > Count for .pdf: 2
>
> > Count for .txt: 4
>
> > Count for .doc: 2
>
> >
>
> That's because each extension can occur multiple times in the list.
>
>
>
> Try the Counter class:
>
>
>
> from collections import Counter
>
>
>
> for ext, count in Counter(extensions).items():
>
> print("Count for %s: " % ext, count)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Function for examine content of directory
kl. 16:56:29 UTC+2 torsdag 6. september 2012 skrev Tigerstyle følgende:
> Hi guys,
>
>
>
> I'm trying to write a module containing a function to examine the contents of
> the current working directory and print out a count of how many files have
> each extension (".txt", ".doc", etc.)
>
>
>
> This is the code so far:
>
> --
>
> import os
>
>
>
> path = "v:\\workspace\\Python2_Homework03\\src\\"
>
> dirs = os.listdir( path )
>
> filenames = {"this.txt", "that.txt",
> "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
>
> extensions = []
>
> for filename in filenames:
>
> f = open(filename, "w")
>
> f.write("Some text\n")
>
> f.close()
>
> name , ext = os.path.splitext(f.name)
>
> extensions.append(ext)
>
>
>
> # This would print all the files and directories
>
> for file in dirs:
>
> print(file)
>
>
>
> for ext in extensions:
>
> print("Count for %s: " %ext, extensions.count(ext))
>
>
>
> --
>
>
>
> When I'm trying to get the module to print how many files each extension has,
> it prints the count of each ext multiple times for each extension type. Like
> this:
>
>
>
> this.pdf
>
> the_other.txt
>
> this.doc
>
> that.txt
>
> this.txt
>
> that.pdf
>
> first.txt
>
> that.doc
>
> Count for .pdf: 2
>
> Count for .txt: 4
>
> Count for .doc: 2
>
> Count for .txt: 4
>
> Count for .txt: 4
>
> Count for .pdf: 2
>
> Count for .txt: 4
>
> Count for .doc: 2
>
>
>
> Any help is appreciated.
>
>
>
> T
--
http://mail.python.org/mailman/listinfo/python-list
Re: Function for examine content of directory
Ok I'm now totally stuck.
This is the code:
---
import os
from collections import Counter
path = ":c\\mypath\dir"
dirs = os.listdir( path )
filenames = {"this.txt", "that.txt",
"the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
extensions = []
for filename in filenames:
f = open(filename, "w")
f.write("Some text\n")
f.close()
name , ext = os.path.splitext(f.name)
extensions.append(ext)
# This would print all the files and directories
for file in dirs:
print(file)
for ext, count in Counter(extensions).items():
print("Count for %s: " % ext, count)
---
I need to make this module into a function and write a separate module to
verify by testing that the function gives correct results.
Help and pointers are much appreciated.
T
--
http://mail.python.org/mailman/listinfo/python-list
Doctest failing
Hi guys.
I'm strugglin with some homework stuff and am hoping you can help me
out here.
This is the code:
small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
def book_title(title):
""" Takes a string and returns a title-case string.
All words EXCEPT for small words are made title case
unless the string starts with a preposition, in which
case the word is correctly capitalized.
>>> book_title('DIVE Into python')
'Dive into Python'
>>> book_title('the great gatsby')
'The Great Gatsby'
>>> book_title('the WORKS OF AleXANDer dumas')
'The Works of Alexander Dumas'
"""
new_title = []
title_split = title.strip().lower().split()
for word in title_split:
if title_split[0] in small_words:
new_title.append(word.title())
elif word in small_words:
new_title.append(word.lower())
else:
new_title.append(word.title())
return(' '.join(new_title))
def _test():
import doctest, refactory
return doctest.testmod(refactory)
if __name__ == "__main__":
_test()
All tests are failing even though I am getting the correct output on
the first two tests. And the last test still gives me "Of" instead of
"of"
Any help is appreciated.
Rgds
T
--
http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 10 Sep, 19:59, Terry Reedy wrote:
> On 9/10/2011 7:20 AM, Tigerstyle wrote:
>
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> We appreciate you saying so instead of hiding that this is homework.
>
>
>
>
>
>
>
>
>
> > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
>
> > def book_title(title):
> > """ Takes a string and returns a title-case string.
> > All words EXCEPT for small words are made title case
> > unless the string starts with a preposition, in which
> > case the word is correctly capitalized.
> > >>> book_title('DIVE Into python')
> > 'Dive into Python'
> > >>> book_title('the great gatsby')
> > 'The Great Gatsby'
> > >>> book_title('the WORKS OF AleXANDer dumas')
> > 'The Works of Alexander Dumas'
> > """
> > new_title = []
> > title_split = title.strip().lower().split()
> > for word in title_split:
> > if title_split[0] in small_words:
> > new_title.append(word.title())
> > elif word in small_words:
> > new_title.append(word.lower())
> > else:
> > new_title.append(word.title())
>
> The key issue is that you want to treat the first word one way (.title
> it) and the rest differently (conditionally .title or not) . So
> immediately separate the first from the rest and then process each.
> There are at least three ways to do the split. Perhaps I should stop
> with this hint, and certainly you should think a bit before reading
> further, but here is what I consider to be the most elegant 3.2 code.
> .
> ,
> ,
> ,
> .
> .
> .
> first, *rest = title.strip().lower().split()
> new_title = [first.title()]
> for word in rest:
> if word not in small_words:
> word = word.title()
> new_title.append(word)
>
> > return(' '.join(new_title))
>
> doctest.testmod() now passes (there is no 'refactory' here)
>
> > def _test():
> > import doctest, refactory
> > return doctest.testmod(refactory)
> > if __name__ == "__main__":
> > _test()
>
> --
> Terry Jan Reedy
Thank you Terry,
I went for this solution as it was the easiest for me to understand
and comment myself keeping in mind what level I am at right now.
Thanks a ton to everyone for sharing so much information and making it
easy to read and understand your thoughts. This was surely very very
educating read the replies from so many talented people.
Thanks and looking forward to hanging around here more :)
T
--
http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 10 Sep, 13:50, Thomas Jollans wrote:
> On 10/09/11 13:20, Tigerstyle wrote:
>
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> > All tests are failing even though I am getting the correct output on
> > the first two tests. And the last test still gives me "Of" instead of
> > "of"
>
> Cannot reproduce. I only get the one, expected, failure.
>
> % python -m doctest books.py
> **
> File "books.py", line 12, in books.book_title
> Failed example:
> book_title('the WORKS OF AleXANDer dumas')
> Expected:
> 'The Works of Alexander Dumas'
> Got:
> 'The Works Of Alexander Dumas'
> **
> 1 items had failures:
> 1 of 3 in books.book_title
> ***Test Failed*** 1 failures.
>
>
>
> > def _test():
> > import doctest, refactory
> > return doctest.testmod(refactory)
> > if __name__ == "__main__":
> > _test()
>
> What is this "refactory"? Are you testing the right code? What is the
> output of your test - does it make sense for the module?
>
> Thomas
Still struggling with my test failing. All 3 tests fail. I'm using
Ecplipse and I think Eclipse is what causing this.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 10 Sep, 13:43, Mel wrote:
> Tigerstyle wrote:
> > Hi guys.
>
> > I'm strugglin with some homework stuff and am hoping you can help me
> > out here.
>
> > This is the code:
>
> > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
>
> > def book_title(title):
> > """ Takes a string and returns a title-case string.
> > All words EXCEPT for small words are made title case
> > unless the string starts with a preposition, in which
> > case the word is correctly capitalized.
> > >>> book_title('DIVE Into python')
> > 'Dive into Python'
> > >>> book_title('the great gatsby')
> > 'The Great Gatsby'
> > >>> book_title('the WORKS OF AleXANDer dumas')
> > 'The Works of Alexander Dumas'
> > """
> > new_title = []
> > title_split = title.strip().lower().split()
> > for word in title_split:
> > if title_split[0] in small_words:
> > new_title.append(word.title())
> > elif word in small_words:
> > new_title.append(word.lower())
> > else:
> > new_title.append(word.title())
> > return(' '.join(new_title))
>
> > def _test():
> > import doctest, refactory
> > return doctest.testmod(refactory)
> > if __name__ == "__main__":
> > _test()
>
> > All tests are failing even though I am getting the correct output on
> > the first two tests. And the last test still gives me "Of" instead of
> > "of"
>
> > Any help is appreciated.
>
> I don't know about doctest -- I suspect it wants a structured docstring to
> specify the tests -- but this
>
> if title_split[0] in small_words:
> new_title.append(word.title())
>
> can't be what you want.
>
> Mel.
Agreed. Not what I need.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 10 Sep, 17:56, Chris Angelico wrote: > On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware > > wrote: > > Ignoring the docttests my process would be to process each word & then > > manually capitalize he 1st word, .I would als0 use a comprehension as > > makes for cleaner code:- > > > def capitalize(word): > > if word in small_words: > > return word > > else: > > return word.title() > > And I'd do this with a lambda, but that's just me. Of course, if your > logic is more complicated, it makes more sense to keep it in a named > function, but a single conditional call can fit nicely into a lambda. > > ChrisA Lambda is too complicated for me to understand yet. Will get there after a little while. Where would you put this piece of code? -- http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 11 Sep, 08:18, Dennis Lee Bieber wrote:
> On Sat, 10 Sep 2011 16:25:42 -0700, Dennis Lee Bieber
> declaimed the following in
> gmane.comp.python.general:
>
>
>
> > in the language documentation... It will give you a simple way to know
> > if you are looking at the first word. Basically, you want to title-case
> > the word IF it is the first word OR the word is NOT in the list of
> > lowercase words; anything else goes through as lower case...
>
> Of course, most of this can be done in a single line (including
> taking into account that some words may have a punctuation mark which
> would confuse the original).
>
> >>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on' ]
> >>> punct = ".,;:?!;'\"(){}[]"
> >>> def recase(str = "physicist odd-affection, or how i was taught to stop
> >>> fretting and adore the weapon of mass destruction"):
>
> ... return " ".join( w.title() if i == 0 or w.strip(punct) not in
> smalls else w
> ... for i,w in enumerate(str.lower().strip().split()) )
> ...>>> recase()
>
> 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting And Adore
> the Weapon of Mass Destruction'>>> recase("what? me worry?")
> 'What? Me Worry?'
> >>> recase("the end of the matter is, to be blunt, a confusion")
>
> 'The End of the Matter Is, To Be Blunt, a Confusion'>>> recase("the end of
> the matter is in, to be blunt, a confusion")
>
> 'The End of the Matter Is in, To Be Blunt, a Confusion'>>> smalls = ['into',
> 'the', 'a', 'of', 'at', 'in', 'for', 'on', "and", "is", "to" ]
> >>> recase()
>
> 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting and Adore
> the Weapon of Mass Destruction'>>> recase("the end of the matter is in, to be
> blunt, a confusion")
>
> 'The End of the Matter is in, to Be Blunt, a Confusion'
>
>
>
> Of course, explaining what this construct is doing is the trick to
> justifying it for a homework assignment.
> --
> Wulfraed Dennis Lee Bieber AF6VN
> [email protected] HTTP://wlfraed.home.netcom.com/
Too much destruction in this post man, and yeah I would not be able to
explain the code for my homework.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Doctest failing
On 11 Sep, 04:12, [email protected] wrote: > On Sep 10, 7:47 am, Peter Otten <[email protected]> wrote: > > > > > > > > > > > Tigerstyle wrote: > > > I'm strugglin with some homework stuff and am hoping you can help me > > > out here. > > > > This is the code: > > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > new_title = [] > > > title_split = title.strip().lower().split() > > > for word in title_split: > > > if title_split[0] in small_words: > > > new_title.append(word.title()) > > > elif word in small_words: > > > new_title.append(word.lower()) > > > else: > > > new_title.append(word.title()) > > > The logic of the for-loop is flawed; the expression > > > title_split[0] in small_words > > > will always evaluate to True if the first word is a "small word", even when > > the loop is already past the first word. You can work around that with a > > flag along these lines > > > first = True > > for word in title_split: > > if first: > > # special treatment for the first word > > first = False > > else: > > # put checks for all words but the first here > > new_title.append(fixed_word) # assuming you have stored the titlecased > > # or lowercased word in the fixed_word > > # variable > > Another way to tackle this is to just capitalize the entire sentence > before returning it. > > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) > return(''.join(new_title).capitalize()) > > However, I'm only helping with your homework, because I want to point > out that doctest comments should be *readable*. Don't just throw them > in, take the extra 10-15 seconds to make them easier on the eyes. In > the workplace, months will pass before you review this code again, so > you want to make it easier for an older version of yourself to > remember it. > > And it takes very little effort to make it readable. Here's your > doctest string, reformatted with just a tiny bit more whitespace. I > even cut out a sentence. > > def book_title(title): > """ > All words EXCEPT for small words are made title case > unless the string starts with a preposition, in which > case the word is correctly capitalized. > > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > -- > // T.Hsu It capitalises the phrase, but still the rest of the phrase is in lower case. -- http://mail.python.org/mailman/listinfo/python-list
