I have a class that looks like that:
class StoryManager:
STORIES = {1:'stories/itsmyluck.txt', 2:'stories/triptothezoo.txt', 3:'stories/loveatfirstsight.txt'}
def get_fields(self, directory):
self.pattern = re.compile(r'<\s*(.*?)\s*>')
self.results = []
with open(directory, 'r', encoding='utf-8') as f:
text = f.read()
self.matches = self.pattern.finditer(text)
for self.match in self.matches:
self.results.append(self.match[1])
return self.results
and another file that I write tests in:
from app import StoryManager
import unittest
class TestStoryManager(unittest.TestCase):
def test_get_fields(self):
result = ['case1','case2','case3','case4','case5','case6',
'case7','case8','case9','case10','case11','case12']
dirs = ['tests/story1.txt', 'tests/story2.txt', 'tests/story3.txt']
self.assertEqual(StoryManager.get_fields(dirs[0]), result)
if __name__ == '__main__':
unittest.main()
and the problem is that python says :
Traceback (most recent call last):
File "d:\Programowanie ;3\GitRepository\madlibs\test_storymanager.py", line 12, in test_get_fields
self.assertEqual(StoryManager.get_fields(dirs[0]), result)
TypeError: get_fields() missing 1 required positional argument: 'directory'
but as I can see there is argument(that is dirs[0]).
I feel like it is something simple but I can't find out what's wrong.
Thanks.
Related
I am trying to read my dictionary(in my file) using ast
import ast
import os
class just_a_class():
def __init__(self, file,):
self.file = file()
self.read_file = open(self.file,'r+')
def read_file(self):
dict = ast.literal_eval(self.read_file.read())
return 'Input: \n\n {}'.format(dict)
the_class = just_a_class("dict.txt")
print(the_class.self.read_file())
Error:
Traceback (most recent call last):
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 13, in <module>
the_class = just_a_class("dict.txt")
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 6, in __init__
self.file = file()
TypeError: 'str' object is not callable
The code below is similar to what is used in the question. I've tried
to improve the readability by using common techniques and conventions,
such as using fname for the filename, instead of file, using a
context manager to open (and auto-close) the file, and capitalization
for class names. Also changed the flags to the open() call to be "r"
instead of "r+", as suggested by ShadowRanger.
import ast
class Just_a_class():
def __init__(self, fname):
self.fname = fname
def read_file(self):
with open(self.fname, 'r') as f:
dict = ast.literal_eval(f.read())
return 'Input: \n\n {}'.format(dict)
the_class = Just_a_class("dict.txt")
print(the_class.read_file())
# {'a': 5, 'b': 'hello'}
My save code is written as so in a file called 'MachLearn.py':
Whilst looking for this code I find out I accidentally overwrote it with an old version :/. It was essentially structured like this:
class attibuteGenerator():
def __init__(self):
#more class stuff
def returnAttributes(self, rating, position):
#func stuff
if __name__ = "__main__":
ag = attributeGenerator():
with open('attributeGenerator_pickle', 'wb') as f:
pickle.dump(f, ag)
My open code is written as so in a file called "mainGame.py"
def main():
with open('attributeGenerator_pickle', 'rb') as f:
bob = pickle.load(f)
print(bob.returnAttributes(34, "LW"))
if __name__ == "__main__":
main()
Is there an issue with my code? It's giving:
This type of error arises when you attempt to unpickle an object, such as a class instance, and you don't have access to the relevant class in your current Python session. You should reimport the packages you were using to generate the objects that you pickled.
The following minimal script will reproduce this problem:
import pickle
class my_class():
def __init__(self):
self.x = 2
inst = my_class()
with open('file.dat', 'wb') as f:
pickle.dump(inst, f); f.close()
del my_class # Deletes the class and causes the problem
with open('file.dat', 'rb') as f:
new_inst = pickle.load(f); f.close()
with error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-6571eae10a31> in <module>
12
13 with open('file.dat', 'rb') as f:
---> 14 new_inst = pickle.load(f); f.close()
AttributeError: Can't get attribute 'my_class' on <module '__main__'>
This can be resolved by removing the line: del my_class.
I have a function that calls a sub-function to open up a file. I am trying to test the parent function, but I want to patch the sub-function and have it return the data I pass in (as if it read from a file).
tests.py
# Read in the sample data
__SAMPLE_LOG = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")
sample_data = []
for line in reversed_lines(open(__SAMPLE_LOG)):
sample_data.append(line)
sample_data = ('').join(sample_data)
class ReadLog(TestCase):
#patch('apps.log_viewer.utils.reversed_lines', new_callable = mock_open, read_data = sample_data)
def test_returnsDictionaryContainingListOfDictionaries(self, mock_file):
activity = read_log()
# Make sure the sample data was read ==> this fails.
self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), sample_data)
utils.py
def read_log():
# This is the line I am trying to patch
for line in reversed_lines(open(settings.ACTIVITY_LOG_FILE)):
# process data
# see: https://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file-in-python/260433#260433
def reversed_lines(file):
"Generate the lines of file in reverse order."
part = ''
for block in reversed_blocks(file):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1]
def reversed_blocks(file, blocksize=4096):
"Generate blocks of file's contents in reverse order."
file.seek(0, os.SEEK_END)
here = file.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
file.seek(here, os.SEEK_SET)
yield file.read(delta)
The error
I am trying to patch reversed_lines() in utils.py within the read_log() method, but read_log() is still reading from the actual log, indicating that I am not patching reversed_lines() correctly.
When I change
#patch('apps.log_viewer.utils.reversed_lines', new_callable = mock_open, read_data = sample_data)
to
#patch('builtins.open', new_callable = mock_open, read_data = sample_data)
I get
======================================================================
ERROR: test_returnsDictionaryContainingListOfDictionaries
(tests.log_viewer.test_utils.ReadLog)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1209, in patched
return func(*args, **keywargs)
File "/webapp/apps/tests/log_viewer/test_utils.py", line 32, in test_returnsDictionaryContainingListOfDictionaries
activity = read_log()
File "/webapp/apps/log_viewer/utils.py", line 64, in read_log
for line in reversed_lines(open(settings.ACTIVITY_LOG_FILE)):
File "/webapp/apps/log_viewer/utils.py", line 173, in reversed_lines
for block in reversed_blocks(file):
File "/webapp/apps/log_viewer/utils.py", line 164, in reversed_blocks
while 0 < here:
TypeError: '<' not supported between instances of 'int' and 'MagicMock'
Where am I going wrong?
Following the example from the docs at https://docs.python.org/3.3/library/unittest.mock.html#mock-open I think you want
#patch('builtins.open', mock_open(read_data = sample_data), create=True)
However reading through the source of mock_open: https://github.com/python/cpython/blob/3.7/Lib/unittest/mock.py#L2350
It appears that the tell method for filehandles is not implemented by the mock. The only supported methods are read, readline, readlines, write and iterating over the contents. You'll need to manually set up the mock for the tell method. This is not a general implementation but will work in your specific case:
class ReadLog(TestCase):
#patch('builtins.open', mock_open(read_data = sample_data), create=True)
def test_returnsDictionaryContainingListOfDictionaries(self, mock_file):
mock_file.return_value.tell.return_value = len(sample_data)
...
I'm trying to organize my code I already have by implementing classes and execute methods on classes instantiations. I have put some hours into figuring out how to use classes, but still haven't figured it out. Could someone help me?
This is the original code:
def readSignalAcquisitionData(fileName):
f = open(fileName, 'r')
# dummy read
f.readline()
timeStamps = []
dataInput = []
for ln in f:
# parse info
timeStr, dataStr = ln.split(',')
timeStamps.append(float(timeStr))
dataInput.append(float(dataStr))
f.close()
return timeStamps, dataInput
And this is what I currently have:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
def readSignalAcquisitionData(self):
f = open(self.fileName, 'r')
self.timeStamps = []
self.dataInput = []
for ln in f:
# parse info
self.timeStr, self.dataStr = ln.split(',')
self.timeStamps.append(float(self.timeStr))
self.dataInput.append(float(self.dataStr))
f.close()
return self.timeStamps, self.dataInput
def writeFilteredData(self, fileName, timeStamps, dataOut):
pass
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
print(timeStamps)
When I try running it through the terminal I get these error messages:
Traceback (most recent call last):
File "SignalDataEvaluationUnit_OOP.py", line 26, in <module>
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
File "SignalDataEvaluationUnit_OOP.py", line 7, in readSignalAcquisitionData
f = open(self.fileName, 'r')
AttributeError: 'str' object has no attribute 'fileName'
As #deceze♦ says in comment, you haven't instantiated the class SignalDataIOUnit, that's why it doesn't work.
To make it work, you have 2 choices:
Instantiating SignalDataIOUnit object and call the method readSignalAcquisitionData:
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
Use Python's #staticmethod decorator:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
#staticmethod
def readSignalAcquisitionData(fileName):
...
then just call it as usual
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
yes, you should use like this
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
print(timeStamps)
Apologize pretty new to python and I'm not 100% sure why this is failing since all example code I see is really similar.
import io
import json
import argparse
from object_detection.helpers import average_bbox
ap = argparse.ArgumentParser()
ap.add_argument("-o","--output",required=True,help="Output file name.")
ap.add_argument("-c","--class",help="Object class name")
ap.add_argument("-a","--annotations",required=True,help="File path annotations are located in")
args = vars(ap.parse_args())
(avgW,avgH) = average_bbox(args["annotations"])
if args["class"] is None:
name = args["annotations"].split("/")[-1]
else:
name = args["class"]
with io.open(args["output"],'w') as f:
o = {}
o["class"] = name
o["avgWidth"] = avgW
o["avgHeight"] = avgH
f.write(json.dumps(o,f))
name, avgW and avgH are all valid values. avgW and avgH are numbers and name is a string. The output seems like a valid path to create a file.
Error I get is
Traceback (most recent call last):
File "compute_average_bbox.py", line 19, in <module>
with io.open(argparse["output"],'w') as f:
TypeError: 'module' object has no attribute '__getitem__'
Any help would be appreciated.