prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def <|fim_middle|>(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | division |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def <|fim_middle|>(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | areatriangulo |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def <|fim_middle|>():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | cast |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def <|fim_middle|>(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | __init__ |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def <|fim_middle|>(self):
return self.nombre
def esMayor(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | hola |
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2
def sumaDos():
print 10*20
def division(a,b):
result=a/b
print result
def areatriangulo(base,altura):
result2=(base*altura)/2
print result2
def cast():
lista=[1,2,3,"hola"]
tupla=(1,2,3)
diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"}
for k,v in diccionario:
print "%s %s" % (k,v)
class Estudiante(object):
def __init__(self, nombre, edad):
self.nombre=nombre
self.edad=edad
def hola(self):
return self.nombre
def <|fim_middle|>(self):
if self.edad>=18:
return true
else:
return false
def EXCEPTION():
try:
3/0
except Exception:
print "error"
def main():
e=Estudiante("Diego",22)
print"Hola %s" % e.hola()
if e.esMayor():
print"Es mayor de edad"
else:
print"Es menor de edad"
contador = 0
while contador <=10:
print contador
contador +=1
EXCEPTION():
def getWeb():
try:
web=urllib2.urlopen("http://itjiquilpan.edu.mx/")
print web.read()
web.close()
except urllib2.HTTPError, e:
print e
except urllib2.URLError as e:
print e
def main():
cast()
if __name__=="__main__":
main()
<|fim▁end|> | esMayor |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
<|fim▁hole|> def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)<|fim▁end|> | |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
<|fim_middle|>
<|fim▁end|> | def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
<|fim_middle|>
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | self.store = store |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
<|fim_middle|>
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
<|fim_middle|>
<|fim▁end|> | metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record) |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
<|fim_middle|>
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | return |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
<|fim_middle|>
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | return |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
<|fim_middle|>
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | continue |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
<|fim_middle|>
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
<|fim_middle|>
self.store.persist(record)
<|fim▁end|> | continue |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def <|fim_middle|>(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | __init__ |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def <|fim_middle|>(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def do(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | parse_record |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from .record import (
Metadata,
Record,
)
__all__ = ['Parser']
class Parser:
def __init__(self, store):
self.store = store
def parse_record(self, metadata, line):
factors = line.split('|')
if len(factors) < 7:
return
registry, cc, type_, start, value, dete, status = factors[:7]
if type_ not in ('ipv4', 'ipv6'):
return
return Record(metadata, start, type_, value, cc)
def <|fim_middle|>(self, fp):
metadata = None
for line in fp:
line = line[:-1]
if line.startswith('#') or line.endswith('summary'):
continue
if metadata is None:
version, registry, serial, records,\
startdate, enddate, utcoffset = line.split('|')[:7]
metadata = Metadata(registry, version, serial)
continue
record = self.parse_record(metadata, line)
if record is None:
continue
self.store.persist(record)
<|fim▁end|> | do |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from django import forms
# future use<|fim▁end|> | |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def termcheck(child, timeout=0):
time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)<|fim▁hole|> except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before
def termkey(child, stream, screen, key, timeout=0):
logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")<|fim▁end|> | |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def termcheck(child, timeout=0):
<|fim_middle|>
def termkey(child, stream, screen, key, timeout=0):
logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")
<|fim▁end|> | time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)
except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def termcheck(child, timeout=0):
time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)
except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before
def termkey(child, stream, screen, key, timeout=0):
<|fim_middle|>
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")
<|fim▁end|> | logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen) |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def <|fim_middle|>(child, timeout=0):
time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)
except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before
def termkey(child, stream, screen, key, timeout=0):
logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")
<|fim▁end|> | termcheck |
<|file_name|>demo3.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import pexpect
import sys
import logging
import vt102
import os
import time
def termcheck(child, timeout=0):
time.sleep(0.05)
try:
logging.debug("Waiting for EOF or timeout=%d"%timeout)
child.expect(pexpect.EOF, timeout=timeout)
except pexpect.exceptions.TIMEOUT:
logging.debug("Hit timeout and have %d characters in child.before"%len(child.before))
return child.before
def <|fim_middle|>(child, stream, screen, key, timeout=0):
logging.debug("Sending '%s' to child"%key)
child.send(key)
s = termcheck(child)
logging.debug("Sending child.before text to vt102 stream")
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
# START LOGGING
logging.basicConfig(filename='menu_demo.log',level=logging.DEBUG)
# SETUP VT102 EMULATOR
#rows, columns = os.popen('stty size', 'r').read().split()
rows, columns = (50,120)
stream=vt102.stream()
screen=vt102.screen((int(rows), int(columns)))
screen.attach(stream)
logging.debug("Setup vt102 with %d %d"%(int(rows),int(columns)))
logging.debug("Starting demo2.py child process...")
child = pexpect.spawn('./demo2.py', maxread=65536, dimensions=(int(rows),int(columns)))
s = termcheck(child)
logging.debug("Sending child.before (len=%d) text to vt102 stream"%len(child.before))
stream.process(child.before)
logging.debug("vt102 screen dump")
logging.debug(screen)
termkey(child, stream, screen, "a")
termkey(child, stream, screen, "1")
logging.debug("Quiting...")
<|fim▁end|> | termkey |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)<|fim▁hole|> u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')<|fim▁end|> |
@task
def launch_instance_from_app_a_image(): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
<|fim_middle|>
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''run ls command on local machine.'''
local('ls -la') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
<|fim_middle|>
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''run ls command on local machine.'''
local('ps ax') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
<|fim_middle|>
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | import sys
print(sys.path) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
<|fim_middle|>
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
<|fim_middle|>
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''print setting from staging.vars and common.vars'''
print(_settings) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
<|fim_middle|>
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | _deploy_template_sample_a(_settings.sample_template_vars.sample_a) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
<|fim_middle|>
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
<|fim_middle|>
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
<|fim_middle|>
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
<|fim_middle|>
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
<|fim_middle|>
<|fim▁end|> | u'''eg. production specific setting'''
print('production_specific_setting') |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def <|fim_middle|>():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | ls |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def <|fim_middle|>():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | ps |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def <|fim_middle|>():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | sys_path |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def <|fim_middle|>():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | sleep |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def <|fim_middle|>():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | printsetting |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def <|fim_middle|>():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | deploy_template_sample_a |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def <|fim_middle|>():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | launch_instance_from_app_a_image |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def <|fim_middle|>():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | set_env_latest_app_a |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def <|fim_middle|>():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | set_env_latest_app_b |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def <|fim_middle|>():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def production_specific_setting():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | launch_instance_from_app_b_image |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*-
from fabric.api import task, run, local, cd, hosts, env
import time
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
import sys
from common_multiple_fabric_environment import _deploy_template_sample_a
test_host = ('192.168.0.110',) #FIXME
@task
def ls():
u'''run ls command on local machine.'''
local('ls -la')
@task
def ps():
u'''run ls command on local machine.'''
local('ps ax')
@task
def sys_path():
import sys
print(sys.path)
@task
def sleep():
u'''sleep 5 second.'''
print('stop 5 sec...')
time.sleep(5)
print('5 sec... passed')
@task
def printsetting():
u'''print setting from staging.vars and common.vars'''
print(_settings)
@task
@hosts(test_host)
def deploy_template_sample_a():
_deploy_template_sample_a(_settings.sample_template_vars.sample_a)
@task
def launch_instance_from_app_a_image():
u'''eg. launch instance from app a image.'''
print('launch_instance_from_app_a_image')
@task
def set_env_latest_app_a():
u'''eg. search latest app type a instance and set fabric env.'''
print('set_env_latest_app_a')
@task
def set_env_latest_app_b():
u'''eg. search latest app type b instance and set fabric env.'''
print('set_env_latest_app_b')
@task
def launch_instance_from_app_b_image():
u'''eg. launch instance from app b image.'''
print('launch_instance_from_app_b_image')
@task
def <|fim_middle|>():
u'''eg. production specific setting'''
print('production_specific_setting')
<|fim▁end|> | production_specific_setting |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""<|fim▁hole|> """
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)<|fim▁end|> | Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists. |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
<|fim_middle|>
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | """
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
<|fim_middle|>
<|fim▁end|> | is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
<|fim_middle|>
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save() |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
<|fim_middle|>
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | """
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
<|fim_middle|>
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
<|fim_middle|>
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
<|fim_middle|>
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path()) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
<|fim_middle|>
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
<|fim_middle|>
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN)) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
<|fim_middle|>
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs)) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
<|fim_middle|>
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertEqual(http_client.OK, response.status_code) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
<|fim_middle|>
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.assertTrue(response.context is not None,
'No context was returned') |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
<|fim_middle|>
<|fim▁end|> | self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
<|fim_middle|>
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save() |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
<|fim_middle|>
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | kwargs['username'] = username |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
<|fim_middle|>
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path()) |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def <|fim_middle|>(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | add_permissions |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def <|fim_middle|>(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | setUp |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def <|fim_middle|>(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | create_user |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def <|fim_middle|>(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | get |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def <|fim_middle|>(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | post |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def <|fim_middle|>(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertIsRedirect |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def <|fim_middle|>(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertRedirectsTo |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def <|fim_middle|>(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertNoAccess |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def <|fim_middle|>(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertRedirectUrlName |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def <|fim_middle|>(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertIsOk |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def <|fim_middle|>(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertContext |
<|file_name|>testcases.py<|end_file_name|><|fim▁begin|>from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = '[email protected]'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def <|fim_middle|>(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
<|fim▁end|> | assertInContext |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|><|fim▁hole|>"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
"""
Adds a cheese tag to the resources object
"""
def __init__(self, **kw):
"""
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw)
def preprocess(self, nb, resources):
"""
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources<|fim▁end|> | """
Contains CheesePreprocessor |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|>"""
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
<|fim_middle|>
<|fim▁end|> | """
Adds a cheese tag to the resources object
"""
def __init__(self, **kw):
"""
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw)
def preprocess(self, nb, resources):
"""
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|>"""
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
"""
Adds a cheese tag to the resources object
"""
def __init__(self, **kw):
<|fim_middle|>
def preprocess(self, nb, resources):
"""
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources
<|fim▁end|> | """
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw) |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|>"""
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
"""
Adds a cheese tag to the resources object
"""
def __init__(self, **kw):
"""
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw)
def preprocess(self, nb, resources):
<|fim_middle|>
<|fim▁end|> | """
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|>"""
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
"""
Adds a cheese tag to the resources object
"""
def <|fim_middle|>(self, **kw):
"""
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw)
def preprocess(self, nb, resources):
"""
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources
<|fim▁end|> | __init__ |
<|file_name|>cheese.py<|end_file_name|><|fim▁begin|>"""
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from ...preprocessors.base import Preprocessor
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class CheesePreprocessor(Preprocessor):
"""
Adds a cheese tag to the resources object
"""
def __init__(self, **kw):
"""
Public constructor
"""
super(CheesePreprocessor, self).__init__(**kw)
def <|fim_middle|>(self, nb, resources):
"""
Sphinx preprocessing to apply on each notebook.
Parameters
----------
nb : NotebookNode
Notebook being converted
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources
<|fim▁end|> | preprocess |
<|file_name|>getting_started_test.py<|end_file_name|><|fim▁begin|># Copyright 2015, Google, 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 re
from getting_started import main
def test_main(cloud_config, capsys):
main(cloud_config.project)
out, _ = capsys.readouterr()
<|fim▁hole|> assert re.search(re.compile(
r'Query Results:.hamlet', re.DOTALL), out)<|fim▁end|> | |
<|file_name|>getting_started_test.py<|end_file_name|><|fim▁begin|># Copyright 2015, Google, 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 re
from getting_started import main
def test_main(cloud_config, capsys):
<|fim_middle|>
<|fim▁end|> | main(cloud_config.project)
out, _ = capsys.readouterr()
assert re.search(re.compile(
r'Query Results:.hamlet', re.DOTALL), out) |
<|file_name|>getting_started_test.py<|end_file_name|><|fim▁begin|># Copyright 2015, Google, 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 re
from getting_started import main
def <|fim_middle|>(cloud_config, capsys):
main(cloud_config.project)
out, _ = capsys.readouterr()
assert re.search(re.compile(
r'Query Results:.hamlet', re.DOTALL), out)
<|fim▁end|> | test_main |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)<|fim▁hole|>
def decode(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
<|fim_middle|>
def decode(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | """Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)
def decode(string, backend=None, keys=False):
<|fim_middle|>
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | """Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
<|fim_middle|>
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)
def decode(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | backend = json |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)
def decode(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
<|fim_middle|>
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | backend = json |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def <|fim_middle|>(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)
def decode(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | encode |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
jsonpickle can take almost any Python object and turn the object into JSON.
Additionally, it can reconstitute the object back into Python.
The object must be accessible globally via a module and must
inherit from object (AKA new-style classes).
Create an object::
class Thing(object):
def __init__(self, name):
self.name = name
obj = Thing('Awesome')
Use jsonpickle to transform the object into a JSON string::
import jsonpickle
frozen = jsonpickle.encode(obj)
Use jsonpickle to recreate a Python object from a JSON string::
thawed = jsonpickle.decode(frozen)
.. warning::
Loading a JSON string from an untrusted source represents a potential
security vulnerability. jsonpickle makes no attempt to sanitize the input.
The new object has the same type and data, but essentially is now a copy of
the original.
.. code-block:: python
assert obj.name == thawed.name
If you will never need to load (regenerate the Python class from JSON), you can
pass in the keyword unpicklable=False to prevent extra information from being
added to JSON::
oneway = jsonpickle.encode(obj, unpicklable=False)
result = jsonpickle.decode(oneway)
assert obj.name == result['name'] == 'Awesome'
"""
import sys, os
from music21 import common
sys.path.append(common.getSourceFilePath() + os.path.sep + 'ext')
from jsonpickle import pickler
from jsonpickle import unpickler
from jsonpickle.backend import JSONBackend
from jsonpickle.version import VERSION
# ensure built-in handlers are loaded
__import__('jsonpickle.handlers')
__all__ = ('encode', 'decode')
__version__ = VERSION
json = JSONBackend()
# Export specific JSONPluginMgr methods into the jsonpickle namespace
set_preferred_backend = json.set_preferred_backend
set_encoder_options = json.set_encoder_options
load_backend = json.load_backend
remove_backend = json.remove_backend
enable_fallthrough = json.enable_fallthrough
def encode(value,
unpicklable=True,
make_refs=True,
keys=False,
max_depth=None,
backend=None,
warn=False,
max_iter=None):
"""Return a JSON formatted representation of value, a Python object.
:param unpicklable: If set to False then the output will not contain the
information necessary to turn the JSON data back into Python objects,
but a simpler JSON stream is produced.
:param max_depth: If set to a non-negative integer then jsonpickle will
not recurse deeper than 'max_depth' steps into the object. Anything
deeper than 'max_depth' is represented using a Python repr() of the
object.
:param make_refs: If set to False jsonpickle's referencing support is
disabled. Objects that are id()-identical won't be preserved across
encode()/decode(), but the resulting JSON stream will be conceptually
simpler. jsonpickle detects cyclical objects and will break the cycle
by calling repr() instead of recursing when make_refs is set False.
:param keys: If set to True then jsonpickle will encode non-string
dictionary keys instead of coercing them into strings via `repr()`.
:param warn: If set to True then jsonpickle will warn when it
returns None for an object which it cannot pickle
(e.g. file descriptors).
:param max_iter: If set to a non-negative integer then jsonpickle will
consume at most `max_iter` items when pickling iterators.
>>> encode('my string')
'"my string"'
>>> encode(36)
'36'
>>> encode({'foo': True})
'{"foo": true}'
>>> encode({'foo': True}, max_depth=0)
'"{\\'foo\\': True}"'
>>> encode({'foo': True}, max_depth=1)
'{"foo": "True"}'
"""
if backend is None:
backend = json
return pickler.encode(value,
backend=backend,
unpicklable=unpicklable,
make_refs=make_refs,
keys=keys,
max_depth=max_depth,
warn=warn)
def <|fim_middle|>(string, backend=None, keys=False):
"""Convert a JSON string into a Python object.
The keyword argument 'keys' defaults to False.
If set to True then jsonpickle will decode non-string dictionary keys
into python objects via the jsonpickle protocol.
>>> str(decode('"my string"'))
'my string'
>>> decode('36')
36
"""
if backend is None:
backend = json
return unpickler.decode(string, backend=backend, keys=keys)
# json.load(),loads(), dump(), dumps() compatibility
dumps = encode
loads = decode
<|fim▁end|> | decode |
<|file_name|>test_wikidata.py<|end_file_name|><|fim▁begin|>def test_signal_wikidata_url(ranker):
rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)
<|fim▁hole|><|fim▁end|> | assert rank("http://www.douglasadams.com") > 0.5
assert rank("http://www.douglasadams.com/?a=b") > 0.5
assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain?
assert rank("http://www.paulherbert.com/") == 0. |
<|file_name|>test_wikidata.py<|end_file_name|><|fim▁begin|>
def test_signal_wikidata_url(ranker):
<|fim_middle|>
<|fim▁end|> | rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)
assert rank("http://www.douglasadams.com") > 0.5
assert rank("http://www.douglasadams.com/?a=b") > 0.5
assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain?
assert rank("http://www.paulherbert.com/") == 0. |
<|file_name|>test_wikidata.py<|end_file_name|><|fim▁begin|>
def <|fim_middle|>(ranker):
rank = lambda url: ranker.client.get_signal_value_from_url("wikidata_url", url)
assert rank("http://www.douglasadams.com") > 0.5
assert rank("http://www.douglasadams.com/?a=b") > 0.5
assert rank("http://www.douglasadams.com/page2") == 0. # TODO, check domain?
assert rank("http://www.paulherbert.com/") == 0.
<|fim▁end|> | test_signal_wikidata_url |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin
#from .models import Tag
#import sys
#import importlib
#importlib.reload(sys)<|fim▁hole|><|fim▁end|> | #admin.site.register(Tag)
# Register your models here. |
<|file_name|>run.py<|end_file_name|><|fim▁begin|>from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from game import app
<|fim▁hole|>http_server.listen(5000)
IOLoop.instance().start()<|fim▁end|> | http_server = HTTPServer(WSGIContainer(app)) |
<|file_name|>ext.py<|end_file_name|><|fim▁begin|>import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout<|fim▁hole|> allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data<|fim▁end|> | r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int): |
<|file_name|>ext.py<|end_file_name|><|fim▁begin|>import json
import logging
from foxglove import glove
from httpx import Response
from .settings import Settings
logger = logging.getLogger('ext')
def lenient_json(v):
<|fim_middle|>
class ApiError(RuntimeError):
def __init__(self, method, url, status, response_text):
self.method = method
self.url = url
self.status = status
self.body = response_text
def __str__(self):
return f'{self.method} {self.url}, unexpected response {self.status}'
class ApiSession:
def __init__(self, root_url, settings: Settings):
self.settings = settings
self.root = root_url.rstrip('/') + '/'
async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data)
async def delete(self, uri, *, allowed_statuses=(200,), **data) -> Response:
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data)
async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response:
return await self._request('PUT', uri, allowed_statuses=allowed_statuses, **data)
async def _request(self, method, uri, allowed_statuses=(200, 201), **data) -> Response:
method, url, data = self._modify_request(method, self.root + str(uri).lstrip('/'), data)
kwargs = {}
headers = data.pop('headers_', None)
if headers is not None:
kwargs['headers'] = headers
if timeout := data.pop('timeout_', None):
kwargs['timeout'] = timeout
r = await glove.http.request(method, url, json=data or None, **kwargs)
if isinstance(allowed_statuses, int):
allowed_statuses = (allowed_statuses,)
if allowed_statuses != '*' and r.status_code not in allowed_statuses:
data = {
'request_real_url': str(r.request.url),
'request_headers': dict(r.request.headers),
'request_data': data,
'response_headers': dict(r.headers),
'response_content': lenient_json(r.text),
}
logger.warning(
'%s unexpected response %s /%s -> %s',
self.__class__.__name__,
method,
uri,
r.status_code,
extra={'data': data} if self.settings.verbose_http_errors else {},
)
raise ApiError(method, url, r.status_code, r.text)
else:
logger.debug('%s /%s -> %s', method, uri, r.status_code)
return r
def _modify_request(self, method, url, data):
return method, url, data
class Mandrill(ApiSession):
def __init__(self, settings):
super().__init__(settings.mandrill_url, settings)
def _modify_request(self, method, url, data):
data['key'] = self.settings.mandrill_key
return method, url, data
class MessageBird(ApiSession):
def __init__(self, settings):
super().__init__(settings.messagebird_url, settings)
def _modify_request(self, method, url, data):
data['headers_'] = {'Authorization': f'AccessKey {self.settings.messagebird_key}'}
return method, url, data
<|fim▁end|> | if isinstance(v, (str, bytes)):
try:
return json.loads(v)
except (ValueError, TypeError):
pass
return v |
Subsets and Splits