prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_cpe_sorter.py<|end_file_name|><|fim▁begin|>import unittest from matching.cpe_sorter import * unsorted_cpes = [{'wfn': {'version': '4.0', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.0:beta:~~~android_marshmallow~~'}, {'wfn': {'version': '1.0.1.2', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:1.0.1.2:beta'}, {'wfn': {'version': '4.1.2', 'target_sw': 'ANY'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'}, {'wfn': {'version': '4.6.3', 'target_sw': 'windows'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.6.3:beta:~~~windows~~'}, {'wfn': {'version': '4.7.1', 'target_sw': 'android'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'}, {'wfn': {'version': '4.7.2', 'target_sw': 'ANY'}, 'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.2:beta'}, {'wfn': {'version': '4.3.2', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'}, {'wfn': {'version': '2.3.1', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2.3.1:beta'}, {'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'} ] unsorted_cpes_year = [{'wfn': {'version': '2000', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2000:beta:~~~android_marshmallow~~'}, {'wfn': {'version': '2007', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2007:beta'}, {'wfn': {'version': '4.1.2', 'target_sw': 'ANY'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'}, {'wfn': {'version': '2010', 'target_sw': 'windows'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~windows~~'}, {'wfn': {'version': '4.7.1', 'target_sw': 'android'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'}, {'wfn': {'version': '2001', 'target_sw': 'ANY'}, 'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:2001:beta'}, {'wfn': {'version': '4.3.2', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'}, {'wfn': {'version': '2010', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta'}, {'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'}, {'wfn': {'version': '2010', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~mac_os_x~~'}] version = '4.7.2' version_without_points = '4_7-2' version_year = '2010' os_windows = 'windows_7' os_linux = 'linux_ubuntu' os_android = 'android' os_mac = 'mac_os_x_10.11' class TestCPESorter(unittest.TestCase): def test_sort_cpes_by_software_version(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes, version) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[5], sorted_cpes[0]) # 4.7.2 self.assertEqual(unsorted_cpes[4], sorted_cpes[1]) # 4.7.1 self.assertEqual(unsorted_cpes[8], sorted_cpes[2]) # 4.7.3 self.assertEqual(unsorted_cpes[0], sorted_cpes[3]) # 4.0 self.assertEqual(unsorted_cpes[2], sorted_cpes[4]) # 4.1.2 self.assertEqual(unsorted_cpes[3], sorted_cpes[5]) # 4.6.3 self.assertEqual(unsorted_cpes[6], sorted_cpes[6]) # 4.3.2 def test_cpes_and_sorted_cpes_are_equal_when_software_version_not_splitted_by_points(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes, version_without_points) self.assertListEqual(unsorted_cpes, sorted_cpes) def test_sort_cpes_by_version_with_year(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes_year, version_year) self.assertEqual(len(unsorted_cpes_year), len(sorted_cpes)) self.assertEqual(unsorted_cpes_year[3], sorted_cpes[0]) # 2010 self.assertEqual(unsorted_cpes_year[7], sorted_cpes[1]) # 2010 self.assertEqual(unsorted_cpes_year[9], sorted_cpes[2]) # 2010 self.assertEqual(unsorted_cpes_year[0], sorted_cpes[3]) # 2000 self.assertEqual(unsorted_cpes_year[1], sorted_cpes[4]) # 2007 self.assertEqual(unsorted_cpes_year[5], sorted_cpes[5]) # 2001 def test_sort_cpes_by_operating_system_windows(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_windows) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[3], sorted_cpes[0]) def test_sort_cpes_by_operating_system_linux(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_linux) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[6], sorted_cpes[0]) def <|fim_middle|>(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_android) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[4], sorted_cpes[0]) self.assertEqual(unsorted_cpes[0], sorted_cpes[1]) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_sort_cpes_by_operating_system_android
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = []<|fim▁hole|> def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure()<|fim▁end|>
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): <|fim_middle|> cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
global frames frames.append(frame)
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): <|fim_middle|> measure() <|fim▁end|>
if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure)
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: <|fim_middle|> global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
QtCore.QTimer.singleShot(100, measure) return
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: <|fim_middle|> else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: <|fim_middle|> QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
global frames frames = []
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def <|fim_middle|>(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
collect
<|file_name|>beamProfiler.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def <|fim_middle|>(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure() <|fim▁end|>
measure
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time <|fim▁hole|> def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg<|fim▁end|>
class MessageHolder(object):
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): <|fim_middle|> def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): <|fim_middle|> def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
self._saved_msg = []
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): <|fim_middle|> def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
self._saved_msg.append(msg)
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): <|fim_middle|> def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
return self._saved_msg
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): <|fim_middle|> def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): <|fim_middle|> # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): <|fim_middle|> # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): <|fim_middle|> # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): <|fim_middle|> <|fim▁end|>
msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def <|fim_middle|>(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
__init__
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def <|fim_middle|>(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
__call__
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def <|fim_middle|>(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
get_msg
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def <|fim_middle|>(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
test_multi_pubsub_once
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def <|fim_middle|>(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
test_to_obj
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def <|fim_middle|>(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
test_to_obj_list
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def <|fim_middle|>(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
test_to_obj_list
<|file_name|>test_utils.py<|end_file_name|><|fim▁begin|>import jps import json import time class MessageHolder(object): def __init__(self): self._saved_msg = [] def __call__(self, msg): self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{"hoge": 1}, {"hogi": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def <|fim_middle|>(): msg = '{"aa": 1, "cc": 3, "bb": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg <|fim▁end|>
test_to_obj_simple
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True)<|fim▁hole|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789")<|fim▁end|>
self.wh.do_proxy.assert_called_with('<socket>')
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): <|fim_middle|> <|fim▁end|>
def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789")
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock()
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>')
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX")
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>')
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX")
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): <|fim_middle|> @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock)
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): <|fim_middle|> <|fim▁end|>
check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789")
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def <|fim_middle|>(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
setUp
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client_token_invalid
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client_novnc
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client_novnc_token_invalid
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client_internal_access_path
<|file_name|>test_websocketproxy.py<|end_file_name|><|fim▁begin|># All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "ws://127.0.0.1/?token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '<socket>' self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = "http://127.0.0.1/" self.wh.headers.getheader.return_value = "token=XXX" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 200 OK\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def <|fim_middle|>(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = "HTTP/1.1 500 Internal Server Error\r\n\r\n" self.wh.socket.return_value = tsock self.wh.path = "ws://127.0.0.1/?token=123-456-789" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token="123-456-789") <|fim▁end|>
test_new_websocket_client_internal_access_path_err
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA:<|fim▁hole|> for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)<|fim▁end|>
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): <|fim_middle|> _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)<|fim▁end|>
v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: <|fim_middle|> else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)<|fim▁end|>
for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1])
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: <|fim_middle|> V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)<|fim▁end|>
print '{}\t{}'.format(V.split(',')[0],V.split(',')[1])
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: <|fim_middle|> <|fim▁end|>
for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def reduction(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: <|fim_middle|> print '{}\t{}'.format(key,V)<|fim▁end|>
print '{}\t{}'.format(K,V)
<|file_name|>reducer.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python import sys sys.path.append('../') from toolbox.hreaders import token_readers as reader from toolbox.hreducers import list_reducer as reducer SOLO_FACTURA = False def <|fim_middle|>(x,y): v1 = x.split(',') v2 = y.split(',') r = x if int(v1[1])>=int(v2[1]) else y return r _reader = reader.Token_reader("\t",1) _reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element if SOLO_FACTURA: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(V.split(',')[0],V.split(',')[1]) V = _reducer.out.split(',') print '{}\t{}'.format(V[0],V[1]) else: for line in sys.stdin: key, value = _reader.read_all(line) K,V = _reducer.reduce(key,value) if K: print '{}\t{}'.format(K,V) print '{}\t{}'.format(key,V)<|fim▁end|>
reduction
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3]<|fim▁hole|> mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()<|fim▁end|>
mapped_seq = list()
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): <|fim_middle|> <|fim▁end|>
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): <|fim_middle|> def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): <|fim_middle|> # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): <|fim_middle|> def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return item + 10
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): <|fim_middle|> def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list.
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): <|fim_middle|> def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers)
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): <|fim_middle|> seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return (item % 2) == 0
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): <|fim_middle|> # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name)
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): <|fim_middle|> names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return len(item) > 4
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): <|fim_middle|> def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return accum + item
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): <|fim_middle|> def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return accum * item
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): <|fim_middle|> # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does.
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): <|fim_middle|> # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
for num in range(1,5): pass self.assertEqual(4, num)
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence <|fim_middle|> <|fim▁end|>
result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): <|fim_middle|> upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
return line.strip().upper()
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def <|fim_middle|>(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_iterators_are_a_type
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def <|fim_middle|>(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_iterating_with_next
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def <|fim_middle|>(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
add_ten
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def <|fim_middle|>(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_map_transforms_elements_of_a_list
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def <|fim_middle|>(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_filter_selects_certain_items_from_a_list
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def <|fim_middle|>(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
is_even
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def <|fim_middle|>(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_just_return_first_item_found
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def <|fim_middle|>(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
is_big_name
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def <|fim_middle|>(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
add
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def <|fim_middle|>(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
multiply
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def <|fim_middle|>(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_reduce_will_blow_your_mind
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def <|fim_middle|>(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_use_pass_for_iterations_with_no_body
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def <|fim_middle|>(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
test_all_iteration_methods_work_on_any_sequence_not_just_lists
<|file_name|>about_iteration.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def <|fim_middle|>(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail() <|fim▁end|>
make_upcase
<|file_name|>kartograph-script.py<|end_file_name|><|fim▁begin|>#!C:\Users\SeanSaito\Dev\aviato\flask\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'kartograph.py==0.6.8','console_scripts','kartograph' __requires__ = 'kartograph.py==0.6.8' import sys<|fim▁hole|>if __name__ == '__main__': sys.exit( load_entry_point('kartograph.py==0.6.8', 'console_scripts', 'kartograph')() )<|fim▁end|>
from pkg_resources import load_entry_point
<|file_name|>kartograph-script.py<|end_file_name|><|fim▁begin|>#!C:\Users\SeanSaito\Dev\aviato\flask\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'kartograph.py==0.6.8','console_scripts','kartograph' __requires__ = 'kartograph.py==0.6.8' import sys from pkg_resources import load_entry_point if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
sys.exit( load_entry_point('kartograph.py==0.6.8', 'console_scripts', 'kartograph')() )
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser):<|fim▁hole|> def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户"<|fim▁end|>
is_staff = False def get_short_name(self): return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): <|fim_middle|> <|fim▁end|>
is_staff = False def get_short_name(self): return self.name def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户"
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def get_short_name(self): <|fim_middle|> def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户" <|fim▁end|>
return self.name
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def get_short_name(self): return self.name def get_full_name(self): <|fim_middle|> USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户" <|fim▁end|>
return self.nickname
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def get_short_name(self): return self.name def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'ex<|fim_middle|> <|fim▁end|>
ample_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户"
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def <|fim_middle|>(self): return self.name def get_full_name(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户" <|fim▁end|>
get_short_name
<|file_name|>models.py<|end_file_name|><|fim▁begin|># encoding: utf-8 from __future__ import absolute_import, unicode_literals from apiview.model import AbstractUserMixin, BaseModel from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractUserMixin, BaseModel, AbstractBaseUser): is_staff = False def get_short_name(self): return self.name def <|fim_middle|>(self): return self.nickname USERNAME_FIELD = 'username' username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False) password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True) nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False) class Meta: db_table = 'example_user' app_label = 'example_app' verbose_name = verbose_name_plural = "用户" <|fim▁end|>
get_full_name
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "corponovo.settings")<|fim▁hole|> try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)<|fim▁end|>
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "corponovo.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form<|fim▁hole|> _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default)<|fim▁end|>
class clv_insured(models.Model):
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): <|fim_middle|> class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): <|fim_middle|> <|fim▁end|>
_inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default)
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): <|fim_middle|> @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals)
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): <|fim_middle|> @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals)
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): <|fim_middle|> <|fim▁end|>
default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default)
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: <|fim_middle|> else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
f = 11 - n
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: <|fim_middle|> code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: code_form = code_str[18 - code_len:21] elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
f = 0
<|file_name|>clv_insured_seq.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################ from openerp import models, fields, api def format_code(code_seq): code = map(int, str(code_seq)) code_len = len(code) while len(code) < 14: code.insert(0, 0) while len(code) < 16: n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11 if n > 1: f = 11 - n else: f = 0 code.append(f) code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]), str(code[2]) + str(code[3]) + str(code[4]), str(code[5]) + str(code[6]) + str(code[7]), str(code[8]) + str(code[9]) + str(code[10]), str(code[11]) + str(code[12]) + str(code[13]), str(code[14]) + str(code[15])) if code_len <= 3: <|fim_middle|> elif code_len > 3 and code_len <= 6: code_form = code_str[17 - code_len:21] elif code_len > 6 and code_len <= 9: code_form = code_str[16 - code_len:21] elif code_len > 9 and code_len <= 12: code_form = code_str[15 - code_len:21] elif code_len > 12 and code_len <= 14: code_form = code_str[14 - code_len:21] return code_form class clv_insured(models.Model): _inherit = 'clv_insured' code = fields.Char('Insured Code', size=64, select=1, required=False, readonly=False, default='/', help='Use "/" to get an automatic new Insured Code.') @api.model def create(self, vals): if not 'code' in vals or ('code' in vals and vals['code'] == '/'): code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).create(vals) @api.multi def write(self, vals): if 'code' in vals and vals['code'] == '/': code_seq = self.pool.get('ir.sequence').get(self._cr, self._uid, 'clv_insured.code') vals['code'] = format_code(code_seq) return super(clv_insured, self).write(vals) @api.one def copy(self, default=None): default = dict(default or {}) default.update({'code': '/',}) return super(clv_insured, self).copy(default) <|fim▁end|>
code_form = code_str[18 - code_len:21]