prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): <|fim_middle|> def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read()
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname)
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
unittest.main()
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def <|fim_middle|>(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
setUp
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def <|fim_middle|>(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_close
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def <|fim_middle|>(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_read
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def <|fim_middle|>(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_seek
<|file_name|>test_arcgis_swm.py<|end_file_name|><|fim▁begin|>import unittest import pysal from pysal.core.IOHandlers.arcgis_swm import ArcGISSwmIO import tempfile import os class test_ArcGISSwmIO(unittest.TestCase): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def <|fim_middle|>(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_write
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>from django.dispatch import Signal <|fim▁hole|>pre_delete = Signal(providing_args=['instance', 'action', ]) post_delete = Signal(providing_args=['instance', 'action', ])<|fim▁end|>
pre_save = Signal(providing_args=['instance', 'action', ]) post_save = Signal(providing_args=['instance', 'action', ])
<|file_name|>P4COMSTR.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test setting the $P4COMSTR variable. """ import os.path import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.subdir('Perforce', ['Perforce', 'sub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """ import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """) test.write('SConstruct', """ def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(TOOLS = ['default', 'Perforce'], BUILDERS={'Cat':Builder(action=cat)}, P4COM='%(_python_)s my-p4.py $TARGET', P4COMSTR='Checking out $TARGET from our fake Perforce') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.Perforce()) SConscript('sub/SConscript', "env") """ % locals()) test.write(['Perforce', 'sub', 'SConscript'], """\ Import("env") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """) test.write(['Perforce', 'aaa.in'], "Perforce/aaa.in\n")<|fim▁hole|>test.write(['Perforce', 'sub', 'ddd.in'], "Perforce/sub/ddd.in\n") test.write(['sub', 'eee.in'], "checked-out sub/eee.in\n") test.write(['Perforce', 'sub', 'fff.in'], "Perforce/sub/fff.in\n") test.run(arguments = '.', stdout = test.wrap_stdout(read_str = """\ Checking out %(sub_SConscript)s from our fake Perforce """ % locals(), build_str = """\ Checking out aaa.in from our fake Perforce cat(["aaa.out"], ["aaa.in"]) cat(["bbb.out"], ["bbb.in"]) Checking out ccc.in from our fake Perforce cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) Checking out %(sub_ddd_in)s from our fake Perforce cat(["%(sub_ddd_out)s"], ["%(sub_ddd_in)s"]) cat(["%(sub_eee_out)s"], ["%(sub_eee_in)s"]) Checking out %(sub_fff_in)s from our fake Perforce cat(["%(sub_fff_out)s"], ["%(sub_fff_in)s"]) cat(["%(sub_all)s"], ["%(sub_ddd_out)s", "%(sub_eee_out)s", "%(sub_fff_out)s"]) """ % locals())) test.must_match('all', "Perforce/aaa.in\nchecked-out bbb.in\nPerforce/ccc.in\n") test.must_match(['sub', 'all'], "Perforce/sub/ddd.in\nchecked-out sub/eee.in\nPerforce/sub/fff.in\n") # test.pass_test()<|fim▁end|>
test.write('bbb.in', "checked-out bbb.in\n") test.write(['Perforce', 'ccc.in'], "Perforce/ccc.in\n")
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()):<|fim▁hole|> if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output)<|fim▁end|>
s = getattr(self.style, action.upper()) action = s(action)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): <|fim_middle|> <|fim▁end|>
def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): <|fim_middle|> def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): <|fim_middle|> def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): <|fim_middle|> <|fim▁end|>
if self.verbose: self.stdout.write(output)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): <|fim_middle|> def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: <|fim_middle|> if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
is_withholding_action = True
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): <|fim_middle|> if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
s = getattr(self.style, action.upper()) action = s(action)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: <|fim_middle|> output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
action = self.style.NOTICE('did not ') + action
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: <|fim_middle|> <|fim▁end|>
self.stdout.write(output)
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def <|fim_middle|>(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
__init__
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def <|fim_middle|>(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
msg
<|file_name|>verbosity.py<|end_file_name|><|fim▁begin|>import os from django.core.management.color import supports_color from django.utils import termcolors class VerboseCommandMixin(object): def __init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def <|fim_middle|>(self, output): if self.verbose: self.stdout.write(output) <|fim▁end|>
log
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id)<|fim▁hole|> @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1<|fim▁end|>
assert not question.their_answer_matches
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): <|fim_middle|> @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): <|fim_middle|> @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): <|fim_middle|> @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR'
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower()
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower()
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower()
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): <|fim_middle|> @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages)
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): <|fim_middle|> @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): <|fim_middle|> @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): <|fim_middle|> @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): <|fim_middle|> @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249]
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): <|fim_middle|> <|fim▁end|>
user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: <|fim_middle|> @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
break
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def <|fim_middle|>(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_age_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def <|fim_middle|>(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_count_variable
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def <|fim_middle|>(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_location_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def <|fim_middle|>(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_search_function
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_search_fetchable_iter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_easy_search_filters
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_children_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_pets_queries
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_height_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def <|fim_middle|>(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_language_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def <|fim_middle|>(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_attractiveness_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def <|fim_middle|>(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_question_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def <|fim_middle|>(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_question_filter_with_custom_answers
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def <|fim_middle|>(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_question_count_filter
<|file_name|>search_test.py<|end_file_name|><|fim▁begin|>import operator import mock import pytest from okcupyd import User from okcupyd import magicnumbers from okcupyd.magicnumbers import maps from okcupyd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = "SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids="wants kids", count=1)[0] assert "wants" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=["has kids"], wants_kids="doesn't want kids", count=0)[0] assert "has kids" in profile.details.children.lower() assert "doesn't want" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6"', height_max='5\'6"', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason="ProfileBuilder needs to be improved to actually get data from profile results") @util.use_cassette def <|fim_middle|>(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 <|fim▁end|>
test_search_populates_upfront
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100:<|fim▁hole|><|fim▁end|>
pass # print unique_values[i]
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): <|fim_middle|> ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i] <|fim▁end|>
text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: <|fim_middle|> words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i] <|fim▁end|>
continue
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: <|fim_middle|> # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i] <|fim▁end|>
print n
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: <|fim_middle|> <|fim▁end|>
pass # print unique_values[i]
<|file_name|>cols_dimensionality.py<|end_file_name|><|fim▁begin|>'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def <|fim_middle|>( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i] <|fim▁end|>
get_words
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame.<|fim▁hole|> g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start()<|fim▁end|>
""" g.setColor('#ff0000')
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): <|fim_middle|> def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() <|fim▁end|>
""" Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame()
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): <|fim_middle|> def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() <|fim▁end|>
""" Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame()
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): <|fim_middle|> <|fim▁end|>
log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start()
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: <|fim_middle|> <|fim▁end|>
q.start()
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def <|fim_middle|>(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() <|fim▁end|>
all_red
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def <|fim_middle|>(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() <|fim▁end|>
all_blue
<|file_name|>alternating_color_fades.py<|end_file_name|><|fim▁begin|>import time, logging from artnet import dmx, fixtures, rig from artnet.dmx import fades log = logging.getLogger(__name__) # set up test fixtures r = rig.get_default_rig() g = r.groups['all'] def all_red(): """ Create an all-red frame. """ g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """ Create an all-blue frame. """ g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def <|fim_middle|>(config, controller=None): log.info("Running script %s" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() <|fim▁end|>
main
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror<|fim▁hole|>----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): <|fim_middle|> #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow')
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): <|fim_middle|> def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') <|fim_middle|> xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
pass
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def <|fim_middle|>(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
main
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def <|fim_middle|>(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def after(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
plot_generator
<|file_name|>04_dE_VCM_bending.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- r""" Bending of collimating mirror ----------------------------- Uses :mod:`shadow` backend. File: `\\examples\\withShadow\\03\\03_DCM_energy.py` Influence onto energy resolution ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pictures after monochromator, :ref:`type 2 of global normalization<globalNorm>`. The nominal radius is 7.4 km. Watch the energy distribution when the bending radius is smaller or greater than the nominal one. +---------+---------+---------+---------+ | |VCMR1| | |VCMR2| | |VCMR3| | | +---------+---------+---------+ |VCMR4| | | |VCMR7| | |VCMR6| | |VCMR5| | | +---------+---------+---------+---------+ .. |VCMR1| image:: _images/03VCM_R0496453_norm2.* :scale: 35 % .. |VCMR2| image:: _images/03VCM_R0568297_norm2.* :scale: 35 % .. |VCMR3| image:: _images/03VCM_R0650537_norm2.* :scale: 35 % .. |VCMR4| image:: _images/03VCM_R0744680_norm2.* :scale: 35 % :align: middle .. |VCMR5| image:: _images/03VCM_R0852445_norm2.* :scale: 35 % .. |VCMR6| image:: _images/03VCM_R0975806_norm2.* :scale: 35 % .. |VCMR7| image:: _images/03VCM_R1117020_norm2.* :scale: 35 % Influence onto focusing ~~~~~~~~~~~~~~~~~~~~~~~ Pictures at the sample position, :ref:`type 1 of global normalization<globalNorm>` +----------+----------+----------+----------+ | |VCMRF1| | |VCMRF2| | |VCMRF3| | | +----------+----------+----------+ |VCMRF4| | | |VCMRF7| | |VCMRF6| | |VCMRF5| | | +----------+----------+----------+----------+ .. |VCMRF1| image:: _images/04VCM_R0496453_norm1.* :scale: 35 % .. |VCMRF2| image:: _images/04VCM_R0568297_norm1.* :scale: 35 % .. |VCMRF3| image:: _images/04VCM_R0650537_norm1.* :scale: 35 % .. |VCMRF4| image:: _images/04VCM_R0744680_norm1.* :scale: 35 % :align: middle .. |VCMRF5| image:: _images/04VCM_R0852445_norm1.* :scale: 35 % .. |VCMRF6| image:: _images/04VCM_R0975806_norm1.* :scale: 35 % .. |VCMRF7| image:: _images/04VCM_R1117020_norm1.* :scale: 35 % """ __author__ = "Konstantin Klementiev" __date__ = "1 Mar 2012" import sys sys.path.append(r"c:\Alba\Ray-tracing\with Python") import numpy as np import xrt.plotter as xrtp import xrt.runner as xrtr import xrt.backends.shadow as shadow def main(): plot1 = xrtp.XYCPlot('star.03') plot1.caxis.offset = 6000 plot2 = xrtp.XYCPlot('star.04') plot2.caxis.offset = 6000 plot1.xaxis.limits = [-15, 15] plot1.yaxis.limits = [-15, 15] plot1.yaxis.factor *= -1 plot2.xaxis.limits = [-1, 1] plot2.yaxis.limits = [-1, 1] plot2.yaxis.factor *= -1 textPanel1 = plot1.fig.text( 0.89, 0.82, '', transform=plot1.fig.transFigure, size=14, color='r', ha='center') textPanel2 = plot2.fig.text( 0.89, 0.82, '', transform=plot2.fig.transFigure, size=14, color='r', ha='center') #========================================================================== threads = 4 #========================================================================== start01 = shadow.files_in_tmp_subdirs('start.01', threads) start04 = shadow.files_in_tmp_subdirs('start.04', threads) rmaj0 = 476597.0 shadow.modify_input(start04, ('R_MAJ', str(rmaj0))) angle = 4.7e-3 tIncidence = 90 - angle * 180 / np.pi shadow.modify_input( start01, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) shadow.modify_input( start04, ('T_INCIDENCE', str(tIncidence)), ('T_REFLECTION', str(tIncidence))) rmirr0 = 744680. def plot_generator(): for rmirr in np.logspace(-1., 1., 7, base=1.5) * rmirr0: shadow.modify_input(start01, ('RMIRR', str(rmirr))) filename = 'VCM_R%07i' % rmirr filename03 = '03' + filename filename04 = '04' + filename plot1.title = filename03 plot2.title = filename04 plot1.saveName = [filename03 + '.pdf', filename03 + '.png'] plot2.saveName = [filename04 + '.pdf', filename04 + '.png'] # plot1.persistentName = filename03 + '.pickle' # plot2.persistentName = filename04 + '.pickle' textToSet = 'collimating\nmirror\n$R =$ %.1f km' % (rmirr * 1e-5) textPanel1.set_text(textToSet) textPanel2.set_text(textToSet) yield def <|fim_middle|>(): # import subprocess # subprocess.call(["python", "05-VFM-bending.py"], # cwd='/home/kklementiev/Alba/Ray-tracing/with Python/05-VFM-bending') pass xrtr.run_ray_tracing( [plot1, plot2], repeats=640, updateEvery=2, energyRange=[5998, 6002], generator=plot_generator, threads=threads, globalNorm=True, afterScript=after, backend='shadow') #this is necessary to use multiprocessing in Windows, otherwise the new Python #contexts cannot be initialized: if __name__ == '__main__': main() <|fim▁end|>
after
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV<|fim▁hole|> ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True)<|fim▁end|>
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): <|fim_middle|> <|fim▁end|>
@mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True)
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): <|fim_middle|> @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout'])
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): <|fim_middle|> @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 )
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): <|fim_middle|> @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True)
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): <|fim_middle|> <|fim▁end|>
wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True)
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def <|fim_middle|>(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
test_action_defaults_from_env
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def <|fim_middle|>(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
test_action_defaults_from_env_not_applied
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def <|fim_middle|>(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
test_with_items_action_defaults_from_env
<|file_name|>test_action_defaults.py<|end_file_name|><|fim▁begin|># Copyright 2015 - StackStorm, Inc. # # 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. import mock from oslo_config import cfg import requests from mistral.actions import std_actions from mistral.db.v2 import api as db_api from mistral.services import workflows as wf_service from mistral.tests.unit import base as test_base from mistral.tests.unit.engine import base from mistral.workflow import states # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') ENV = { '__actions': { 'std.http': { 'auth': 'librarian:password123', 'timeout': 30, } } } EXPECTED_ENV_AUTH = ('librarian', 'password123') WORKFLOW1 = """ --- version: "2.0" wf1: type: direct tasks: task1: action: std.http url="https://api.library.org/books" publish: result: <% $ %> """ WORKFLOW2 = """ --- version: "2.0" wf2: type: direct tasks: task1: action: std.http url="https://api.library.org/books" timeout=60 publish: result: <% $ %> """ WORKFLOW1_WITH_ITEMS = """ --- version: "2.0" wf1_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> publish: result: <% $ %> """ WORKFLOW2_WITH_ITEMS = """ --- version: "2.0" wf2_with_items: type: direct input: - links tasks: task1: with-items: link in <% $.links %> action: std.http url=<% $.link %> timeout=60 publish: result: <% $ %> """ class ActionDefaultTest(base.EngineTestCase): @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1) wf_ex = self.engine.start_workflow('wf1', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=ENV['__actions']['std.http']['timeout']) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_action_defaults_from_env_not_applied(self): wf_service.create_workflows(WORKFLOW2) wf_ex = self.engine.start_workflow('wf2', env=ENV) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') requests.request.assert_called_with( 'GET', 'https://api.library.org/books', params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, verify=None, auth=EXPECTED_ENV_AUTH, timeout=60 ) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def test_with_items_action_defaults_from_env(self): wf_service.create_workflows(WORKFLOW1_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf1_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=ENV['__actions']['std.http']['timeout']) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) @mock.patch.object( requests, 'request', mock.MagicMock(return_value=test_base.FakeHTTPResponse('', 200, 'OK'))) @mock.patch.object( std_actions.HTTPAction, 'is_sync', mock.MagicMock(return_value=True)) def <|fim_middle|>(self): wf_service.create_workflows(WORKFLOW2_WITH_ITEMS) wf_input = { 'links': [ 'https://api.library.org/books', 'https://api.library.org/authors' ] } wf_ex = self.engine.start_workflow( 'wf2_with_items', wf_input=wf_input, env=ENV ) self.await_workflow_success(wf_ex.id) with db_api.transaction(): wf_ex = db_api.get_workflow_execution(wf_ex.id) self.assertEqual(states.SUCCESS, wf_ex.state) self._assert_single_item(wf_ex.task_executions, name='task1') calls = [mock.call('GET', url, params=None, data=None, headers=None, cookies=None, allow_redirects=None, proxies=None, auth=EXPECTED_ENV_AUTH, verify=None, timeout=60) for url in wf_input['links']] requests.request.assert_has_calls(calls, any_order=True) <|fim▁end|>
test_with_items_action_defaults_from_env_not_applied
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from osweb.projects.ManageProject import ManageProject from osweb.projects.projects_data import ProjectsData
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int]<|fim▁hole|> :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1))<|fim▁end|>
:type k: int :type t: int
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): <|fim_middle|> test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): <|fim_middle|> test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
""" :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: <|fim_middle|> dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
return False
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: <|fim_middle|> m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
del dic[nums[i - k - 1] // t]
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: <|fim_middle|> if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
return True
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: <|fim_middle|> if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
return True
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: <|fim_middle|> dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
return True
<|file_name|>220 Contains Duplicate III.py<|end_file_name|><|fim▁begin|>class Solution(object): def <|fim_middle|>(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) <|fim▁end|>
containsNearbyAlmostDuplicate
<|file_name|>uicommon.py<|end_file_name|><|fim▁begin|>def emptyLayout(layout): for i in reversed(range(layout.count())):<|fim▁hole|><|fim▁end|>
layout.itemAt(i).widget().setParent(None)
<|file_name|>uicommon.py<|end_file_name|><|fim▁begin|>def emptyLayout(layout): <|fim_middle|> <|fim▁end|>
for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None)
<|file_name|>uicommon.py<|end_file_name|><|fim▁begin|>def <|fim_middle|>(layout): for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) <|fim▁end|>
emptyLayout