function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def idq_torque(id, iq, torque, ax=0):
"""creates a surface plot of torque vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
_plot_surface(ax, id, iq, scale*np.asarray(torque),
(u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)),
azim=-60)
return ax | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def idq_psiq(id, iq, psiq, ax=0):
"""creates a surface plot of psiq vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psiq,
(u'Id/A', u'Iq/A', u'Psi q/Vs'),
azim=210) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def idq_ld(id, iq, ld, ax=0):
"""creates a surface plot of ld vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, np.asarray(ld)*1e3,
(u'Id/A', u'Iq/A', u'L d/mH'),
azim=120) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def ldlq(bch):
"""creates the surface plots of a BCH reader object
with a ld-lq identification"""
beta = bch.ldq['beta']
i1 = bch.ldq['i1']
torque = bch.ldq['torque']
ld = np.array(bch.ldq['ld'])
lq = np.array(bch.ldq['lq'])
psid = bch.ldq['psid']
psiq = bch.ldq['psiq']
rows = 3
fig = plt.figure(figsize=(10, 4*rows))
fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16)
fig.add_subplot(rows, 2, 1, projection='3d')
i1beta_torque(i1, beta, torque)
fig.add_subplot(rows, 2, 2, projection='3d')
i1beta_psid(i1, beta, psid)
fig.add_subplot(rows, 2, 3, projection='3d')
i1beta_psiq(i1, beta, psiq)
fig.add_subplot(rows, 2, 4, projection='3d')
try:
i1beta_psim(i1, beta, bch.ldq['psim'])
except:
i1beta_up(i1, beta, bch.ldq['up'])
fig.add_subplot(rows, 2, 5, projection='3d')
i1beta_ld(i1, beta, ld)
fig.add_subplot(rows, 2, 6, projection='3d')
i1beta_lq(i1, beta, lq) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def felosses(losses, coeffs, title='', log=True, ax=0):
"""plot iron losses with steinmetz or jordan approximation
Args:
losses: dict with f, B, pfe values
coeffs: list with steinmetz (cw, alpha, beta) or
jordan (cw, alpha, ch, beta, gamma) coeffs
title: title string
log: log scale for x and y axes if True
"""
import femagtools.losscoeffs as lc
if ax == 0:
ax = plt.gca()
fo = losses['fo']
Bo = losses['Bo']
B = plt.np.linspace(0.9*np.min(losses['B']),
1.1*0.9*np.max(losses['B']))
for i, f in enumerate(losses['f']):
pfe = [p for p in np.array(losses['pfe'])[i] if p]
if f > 0:
if len(coeffs) == 5:
ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo))
elif len(coeffs) == 3:
ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo))
plt.plot(losses['B'][:len(pfe)], pfe,
marker='o', label="{} Hz".format(f))
ax.set_title("Fe Losses/(W/kg) " + title)
if log:
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel("Flux Density [T]")
# plt.ylabel("Pfe [W/kg]")
ax.legend()
ax.grid(True) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def mesh(isa, with_axis=False, ax=0):
"""plot mesh of I7/ISA7 model
Args:
isa: Isa7 object
"""
from matplotlib.lines import Line2D
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
for el in isa.elements:
pts = [list(i) for i in zip(*[v.xy for v in el.vertices])]
ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25))
# for nc in isa.nodechains:
# pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])]
# ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25,
# marker=".", ms="2", mec="None"))
# for nc in isa.nodechains:
# if nc.nodemid is not None:
# plt.plot(*nc.nodemid.xy, "rx")
ax.autoscale(enable=True)
if not with_axis:
ax.axis('off') | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def demag(isa, ax=0):
"""plot demag of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
emag = [e for e in isa.elements if e.is_magnet()]
demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag])
_contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C',
emag, demag, '-H / kA/m', isa)
logger.info("Max demagnetization %f", np.max(demag)) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def flux_density(isa, subreg=[], ax=0):
"""plot flux density of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
if subreg:
if isinstance(subreg, list):
sr = subreg
else:
sr = [subreg]
elements = [e for s in sr for se in isa.get_subregion(s).elements()
for e in se]
else:
elements = [e for e in isa.elements]
fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements])
_contour(ax, f'Flux Density T', elements, fluxd)
logger.info("Max flux dens %f", np.max(fluxd)) | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def mmf(f, title='', ax=0):
"""plot magnetomotive force (mmf) of winding"""
if ax == 0:
ax = plt.gca()
if title:
ax.set_title(title)
ax.plot(np.array(f['pos'])/np.pi*180, f['mmf'])
ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft'])
ax.set_xlabel('Position / Deg')
phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180]
y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])]
ax.plot(phi, y, '--')
alfa0 = round(f['alfa0']/np.pi*180, 3)
ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°",
ha="center", va="bottom")
ax.annotate(f"", xy=(phi[0], y[0]),
xytext=(0, y[0]), arrowprops=dict(arrowstyle="->"))
ax.grid() | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def zoneplan(wdg, ax=0):
"""plot zone plan of winding wdg"""
from matplotlib.patches import Rectangle
upper, lower = wdg.zoneplan()
Qb = len([n for l in upper for n in l])
from femagtools.windings import coil_color
rh = 0.5
if lower:
yl = rh
ymax = 2*rh + 0.2
else:
yl = 0
ymax = rh + 0.2
if ax == 0:
ax = plt.gca()
ax.axis('off')
ax.set_xlim([-0.5, Qb-0.5])
ax.set_ylim([0, ymax])
ax.set_aspect(Qb/6+0.3)
for i, p in enumerate(upper):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl+rh/2, s, color='black',
ha="center", va="center")
for i, p in enumerate(lower):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl-rh/2, s, color='black',
ha="center", va="center")
yu = yl+rh
step = 1 if Qb < 25 else 2
if lower:
yl -= rh
margin = 0.05
ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}',
ha='left', va='bottom', size=15)
for i in range(0, Qb, step):
ax.text(i, yl-margin, f'{i+1}', ha="center", va="top") | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def winding(wdg, ax=0):
"""plot coils of windings wdg"""
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
from femagtools.windings import coil_color
coil_len = 25
coil_height = 4
dslot = 8
arrow_head_length = 2
arrow_head_width = 2
if ax == 0:
ax = plt.gca()
z = wdg.zoneplan()
xoff = 0
if z[-1]:
xoff = 0.75
yd = dslot*wdg.yd
mh = 2*coil_height/yd
slots = sorted([abs(n) for m in z[0] for n in m])
smax = slots[-1]*dslot
for n in slots:
x = n*dslot
ax.add_patch(Rectangle((x + dslot/4, 1), dslot /
2, coil_len - 2, fc="lightblue"))
ax.text(x, coil_len / 2,
str(n),
horizontalalignment="center",
verticalalignment="center",
backgroundcolor="white",
bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0))
line_thickness = [0.6, 1.2]
for i, layer in enumerate(z):
b = -xoff if i else xoff
lw = line_thickness[i]
for m, mslots in enumerate(layer):
for k in mslots:
x = abs(k) * dslot + b
xpoints = []
ypoints = []
if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))):
# first layer, positive dir or neg. dir and 2-layers:
# from right bottom
if x + yd > smax+b:
dx = dslot if yd > dslot else yd/4
xpoints = [x + yd//2 + dx - xoff]
ypoints = [-coil_height + mh*dx]
xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x + yd > smax+b:
xpoints += [x + yd//2 + dx - xoff]
ypoints += [coil_len+coil_height - mh*dx]
else:
# from left bottom
if x - yd < 0: # and x - yd/2 > -3*dslot:
dx = dslot if yd > dslot else yd/4
xpoints = [x - yd//2 - dx + xoff]
ypoints = [- coil_height + mh*dx]
xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x - yd < 0: # and x - yd > -3*dslot:
xpoints += [x - yd//2 - dx + xoff]
ypoints += [coil_len + coil_height - mh*dx]
ax.add_line(Line2D(xpoints, ypoints,
color=coil_color[m], lw=lw))
if k > 0:
h = arrow_head_length
y = coil_len * 0.8
else:
h = -arrow_head_length
y = coil_len * 0.2
ax.arrow(x, y, 0, h,
length_includes_head=True,
head_starts_at_zero=False,
head_length=arrow_head_length,
head_width=arrow_head_width,
fc=coil_color[m], lw=0)
if False: # TODO show winding connections
m = 0
for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]:
if k < len(slots):
x = k * dslot + b + yd/2 - xoff
ax.add_line(Line2D([x, x],
[-2*coil_height, -coil_height],
color=coil_color[m], lw=lw))
ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m])
m += 1
ax.autoscale(enable=True)
ax.set_axis_off() | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def characteristics(char, title=''):
fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True)
if title:
fig.suptitle(title)
n = np.array(char['n'])*60
pmech = np.array(char['pmech'])*1e-3
axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque')
axs[0, 0].set_ylabel("Torque / Nm")
axs[0, 0].grid()
axs[0, 0].legend(loc='center left')
ax1 = axs[0, 0].twinx()
ax1.plot(n, pmech, 'C1-', label='P mech')
ax1.set_ylabel("Power / kW")
ax1.legend(loc='lower center')
axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage')
axs[0, 1].set_ylabel("Voltage / V",)
axs[0, 1].grid()
axs[0, 1].legend(loc='center left')
ax2 = axs[0, 1].twinx()
ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi')
ax2.set_ylabel("Cos Phi")
ax2.legend(loc='lower right')
if 'id' in char:
axs[1, 0].plot(n, np.array(char['id']), label='Id')
if 'iq' in char:
axs[1, 0].plot(n, np.array(char['iq']), label='Iq')
axs[1, 0].plot(n, np.array(char['i1']), label='I1')
axs[1, 0].set_xlabel("Speed / rpm")
axs[1, 0].set_ylabel("Current / A")
axs[1, 0].legend(loc='center left')
if 'beta' in char:
ax3 = axs[1, 0].twinx()
ax3.plot(n, char['beta'], 'C3-', label='Beta')
ax3.set_ylabel("Beta / °")
ax3.legend(loc='center right')
axs[1, 0].grid()
plfe = np.array(char['plfe'])*1e-3
plcu = np.array(char['plcu'])*1e-3
pl = np.array(char['losses'])*1e-3
axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses')
axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses')
axs[1, 1].set_ylabel("Losses / kW")
axs[1, 1].legend(loc='center left')
axs[1, 1].grid()
axs[1, 1].set_xlabel("Speed / rpm")
ax4 = axs[1, 1].twinx()
ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta")
ax4.legend(loc='upper center')
ax4.set_ylabel("Efficiency")
fig.tight_layout() | SEMAFORInformatik/femagtools | [
17,
10,
17,
4,
1471511034
] |
def __init__(self, out='noise', realization=0, component=0, noise='noise',
rate=None, altFFT=False):
# We call the parent class constructor, which currently does nothing
super().__init__()
self._out = out
self._oversample = 2
self._realization = realization
self._component = component
self._noisekey = noise
self._rate = rate
self._altfft = altFFT | tskisner/pytoast | [
29,
32,
29,
55,
1428597089
] |
def test_scaffold(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (),
}
}) | praekelt/molo | [
26,
5,
26,
12,
1432888733
] |
def test_scaffold_with_custom_dir(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', 'bar'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'bar',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (),
}
}) | praekelt/molo | [
26,
5,
26,
12,
1432888733
] |
def test_scaffold_with_requirements(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', '--require', 'bar'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': ('bar',),
'include': (),
}
}) | praekelt/molo | [
26,
5,
26,
12,
1432888733
] |
def test_scaffold_with_includes(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', '--include', 'bar', 'baz'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (('bar', 'baz'),),
}
}) | praekelt/molo | [
26,
5,
26,
12,
1432888733
] |
def test_unpack(self, mock_copytree, mock_get_template_dirs,
mock_get_package):
package = pkg_resources.get_distribution('molo.core')
mock_get_package.return_value = package
mock_get_template_dirs.return_value = ['foo']
mock_copytree.return_value = True
from molo.core.scripts import cli
runner = CliRunner()
runner.invoke(cli.unpack_templates, ['app1', 'app2'])
mock_copytree.assert_called_with(
pkg_resources.resource_filename('molo.core', 'templates/foo'),
pkg_resources.resource_filename('molo.core', 'templates/foo')) | praekelt/molo | [
26,
5,
26,
12,
1432888733
] |
def test_version_constants(self, space):
w_res = space.execute("return Marshal::MAJOR_VERSION")
assert space.int_w(w_res) == 4
w_res = space.execute("return Marshal::MINOR_VERSION")
assert space.int_w(w_res) == 8
w_res = space.execute("return Marshal.dump('test')[0].ord")
assert space.int_w(w_res) == 4
w_res = space.execute("return Marshal.dump('test')[1].ord")
assert space.int_w(w_res) == 8 | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_load_constants(self, space):
w_res = space.execute("return Marshal.load('\x04\b0')")
assert w_res == space.w_nil
w_res = space.execute("return Marshal.load('\x04\bT')")
assert w_res == space.w_true
w_res = space.execute("return Marshal.load('\x04\bF')")
assert w_res == space.w_false | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_tiny_integer(self, space):
w_res = space.execute("return Marshal.dump(5)")
assert space.str_w(w_res) == "\x04\bi\n"
w_res = space.execute("return Marshal.dump(100)")
assert space.str_w(w_res) == "\x04\bii"
w_res = space.execute("return Marshal.dump(0)")
assert space.str_w(w_res) == "\x04\bi\x00"
w_res = space.execute("return Marshal.dump(-1)")
assert space.str_w(w_res) == "\x04\bi\xFA"
w_res = space.execute("return Marshal.dump(-123)")
assert space.str_w(w_res) == "\x04\bi\x80"
w_res = space.execute("return Marshal.dump(122)")
assert space.str_w(w_res) == "\x04\bi\x7F" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_array(self, space):
w_res = space.execute("return Marshal.dump([])")
assert space.str_w(w_res) == "\x04\b[\x00"
w_res = space.execute("return Marshal.dump([nil])")
assert space.str_w(w_res) == "\x04\b[\x060"
w_res = space.execute("return Marshal.dump([nil, true, false])")
assert space.str_w(w_res) == "\x04\b[\b0TF"
w_res = space.execute("return Marshal.dump([1, 2, 3])")
assert space.str_w(w_res) == "\x04\b[\x08i\x06i\x07i\x08"
w_res = space.execute("return Marshal.dump([1, [2, 3], 4])")
assert space.str_w(w_res) == "\x04\b[\bi\x06[\ai\ai\bi\t"
w_res = space.execute("return Marshal.dump([:foo, :bar])")
assert space.str_w(w_res) == "\x04\b[\a:\bfoo:\bbar" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_symbol(self, space):
w_res = space.execute("return Marshal.dump(:abc)")
assert space.str_w(w_res) == "\x04\b:\babc"
w_res = space.execute("return Marshal.dump(('hello' * 25).to_sym)")
assert space.str_w(w_res) == "\x04\b:\x01}" + "hello" * 25
w_res = space.execute("return Marshal.dump(('hello' * 100).to_sym)")
assert space.str_w(w_res) == "\x04\b:\x02\xF4\x01" + "hello" * 100 | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_hash(self, space):
w_res = space.execute("return Marshal.dump({})")
assert space.str_w(w_res) == "\x04\b{\x00"
w_res = space.execute("return Marshal.dump({1 => 2, 3 => 4})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x06i\ai\bi\t"
w_res = space.execute("return Marshal.dump({1 => {2 => 3}, 4 => 5})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x06{\x06i\ai\bi\ti\n"
w_res = space.execute("return Marshal.dump({1234 => {23456 => 3456789}, 4 => 5})")
assert self.unwrap(space, w_res) == "\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_integer(self, space):
w_res = space.execute("return Marshal.dump(123)")
assert space.str_w(w_res) == "\x04\bi\x01{"
w_res = space.execute("return Marshal.dump(255)")
assert space.str_w(w_res) == "\x04\bi\x01\xFF"
w_res = space.execute("return Marshal.dump(256)")
assert space.str_w(w_res) == "\x04\bi\x02\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 16 - 2)")
assert space.str_w(w_res) == "\x04\bi\x02\xFE\xFF"
w_res = space.execute("return Marshal.dump(2 ** 16 - 1)")
assert space.str_w(w_res) == "\x04\bi\x02\xFF\xFF"
w_res = space.execute("return Marshal.dump(2 ** 16)")
assert space.str_w(w_res) == "\x04\bi\x03\x00\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 16 + 1)")
assert space.str_w(w_res) == "\x04\bi\x03\x01\x00\x01"
w_res = space.execute("return Marshal.dump(2 ** 30 - 1)")
assert space.str_w(w_res) == "\x04\bi\x04\xFF\xFF\xFF?"
# TODO: test tooo big numbers (they give a warning and inf) | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_negative_integer(self, space):
w_res = space.execute("return Marshal.dump(-1)")
assert space.str_w(w_res) == "\x04\bi\xFA"
w_res = space.execute("return Marshal.dump(-123)")
assert space.str_w(w_res) == "\x04\bi\x80"
w_res = space.execute("return Marshal.dump(-124)")
assert space.str_w(w_res) == "\x04\bi\xFF\x84"
w_res = space.execute("return Marshal.dump(-256)")
assert space.str_w(w_res) == "\x04\bi\xFF\x00"
w_res = space.execute("return Marshal.dump(-257)")
assert space.str_w(w_res) == "\x04\bi\xFE\xFF\xFE"
w_res = space.execute("return Marshal.dump(-(2 ** 30))")
assert space.str_w(w_res) == "\x04\bi\xFC\x00\x00\x00\xC0" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_float(self, space):
w_res = space.execute("return Marshal.dump(0.0)")
assert space.str_w(w_res) == "\x04\bf\x060"
w_res = space.execute("return Marshal.dump(0.1)")
assert space.str_w(w_res) == "\x04\bf\b0.1"
w_res = space.execute("return Marshal.dump(1.0)")
assert space.str_w(w_res) == "\x04\bf\x061"
w_res = space.execute("return Marshal.dump(1.1)")
assert space.str_w(w_res) == "\x04\bf\b1.1"
w_res = space.execute("return Marshal.dump(1.001)")
assert space.str_w(w_res) == "\x04\bf\n1.001"
#w_res = space.execute("return Marshal.dump(123456789.123456789)")
#assert space.str_w(w_res) == "\x04\bf\x17123456789.12345679"
#w_res = space.execute("return Marshal.dump(-123456789.123456789)")
#assert space.str_w(w_res) == "\x04\bf\x18-123456789.12345679"
#w_res = space.execute("return Marshal.dump(-0.0)")
#assert space.str_w(w_res) == "\x04\bf\a-0" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_dump_string(self, space):
w_res = space.execute("return Marshal.dump('')")
assert space.str_w(w_res) == "\x04\bI\"\x00\x06:\x06ET"
w_res = space.execute("return Marshal.dump('abc')")
assert space.str_w(w_res) == "\x04\bI\"\babc\x06:\x06ET"
w_res = space.execute("return Marshal.dump('i am a longer string')")
assert space.str_w(w_res) == "\x04\bI\"\x19i am a longer string\x06:\x06ET" | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_array(self, space):
w_res = space.execute("return Marshal.load(Marshal.dump([1, 2, 3]))")
assert self.unwrap(space, w_res) == [1, 2, 3]
w_res = space.execute("return Marshal.load(Marshal.dump([1, [2, 3], 4]))")
assert self.unwrap(space, w_res) == [1, [2, 3], 4]
w_res = space.execute("return Marshal.load(Marshal.dump([130, [2, 3], 4]))")
assert self.unwrap(space, w_res) == [130, [2, 3], 4]
w_res = space.execute("return Marshal.load(Marshal.dump([-10000, [2, 123456], -9000]))")
assert self.unwrap(space, w_res) == [-10000, [2, 123456], -9000]
w_res = space.execute("return Marshal.load(Marshal.dump([:foo, :bar]))")
assert self.unwrap(space, w_res) == ["foo", "bar"]
w_res = space.execute("return Marshal.load(Marshal.dump(['foo', 'bar']))")
assert self.unwrap(space, w_res) == ["foo", "bar"] | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def test_short_data(self, space):
with self.raises(space, "ArgumentError", "marshal data too short"):
space.execute("Marshal.load('')") | babelsberg/babelsberg-r | [
19,
2,
19,
1,
1346685898
] |
def md5(file_path):
"""Get md5 hash of a file.
Parameters
----------
file_path: str
File path.
Returns
-------
md5_hash: str
md5 hash of data in file_path
"""
hash_md5 = hashlib.md5()
with open(file_path, 'rb') as fhandle:
for chunk in iter(lambda: fhandle.read(4096), b''):
hash_md5.update(chunk)
return hash_md5.hexdigest() | mir-dataset-loaders/mirdata | [
273,
52,
273,
69,
1550182293
] |
def make_irmas_index(irmas_data_path):
count = 0
irmas_dict = dict()
for root, dirs, files in os.walk(irmas_data_path):
for directory in dirs:
if 'Train' in directory:
for root_, dirs_, files_ in os.walk(
os.path.join(irmas_data_path, directory)
):
for directory_ in dirs_:
for root__, dirs__, files__ in os.walk(
os.path.join(irmas_data_path, directory, directory_)
):
for file in files__:
if file.endswith('.wav'):
if 'dru' in file:
irmas_id_dru = file.split(']')[3] # Obtain id
irmas_id_dru_no_wav = irmas_id_dru.split('.')[
0
] # Obtain id without '.wav'
irmas_dict[irmas_id_dru_no_wav] = os.path.join(
directory, directory_, file
)
if 'nod' in file:
irmas_id_nod = file.split(']')[3] # Obtain id
irmas_id_nod_no_wav = irmas_id_nod.split('.')[
0
] # Obtain id without '.wav'
irmas_dict[irmas_id_nod_no_wav] = os.path.join(
directory, directory_, file
)
else:
irmas_id = file.split(']')[2] # Obtain id
irmas_id_no_wav = irmas_id.split('.')[
0
] # Obtain id without '.wav'
irmas_dict[irmas_id_no_wav] = os.path.join(
directory, directory_, file
)
irmas_test_dict = dict()
for root, dirs, files in os.walk(irmas_data_path):
for directory in dirs:
if 'Test' in directory:
for root_, dirs_, files_ in os.walk(
os.path.join(irmas_data_path, directory)
):
for directory_ in dirs_:
for root__, dirs__, files__ in os.walk(
os.path.join(irmas_data_path, directory, directory_)
):
for file in files__:
if file.endswith('.wav'):
file_name = os.path.join(
directory, directory_, file
)
track_name = str(file_name.split('.wa')[0]) + '.txt'
irmas_test_dict[count] = [file_name, track_name]
count += 1
irmas_id_list = sorted(irmas_dict.items()) # Sort strokes by id
irmas_index = {}
for inst in irmas_id_list:
print(inst[1])
audio_checksum = md5(os.path.join(irmas_data_path, inst[1]))
irmas_index[inst[0]] = {
'audio': (inst[1], audio_checksum),
'annotation': (inst[1], audio_checksum),
}
index = 1
for inst in irmas_test_dict.values():
audio_checksum = md5(os.path.join(irmas_data_path, inst[0]))
annotation_checksum = md5(os.path.join(irmas_data_path, inst[1]))
irmas_index[index] = {
'audio': (inst[0], audio_checksum),
'annotation': (inst[1], annotation_checksum),
}
index += 1
with open(IRMAS_INDEX_PATH, 'w') as fhandle:
json.dump(irmas_index, fhandle, indent=2) | mir-dataset-loaders/mirdata | [
273,
52,
273,
69,
1550182293
] |
def main(args):
make_irmas_index(args.irmas_data_path)
# make_irmas_test_index(args.irmas_data_path) | mir-dataset-loaders/mirdata | [
273,
52,
273,
69,
1550182293
] |
def setUp(self):
self.app_helper = self.add_helper(AppWorkerHelper(StreamingHTTPWorker))
self.config = {
'health_path': '/health/',
'web_path': '/foo',
'web_port': 0,
'metrics_prefix': 'metrics_prefix.',
'conversation_cache_ttl': 0,
}
self.app = yield self.app_helper.get_app_worker(self.config)
self.addr = self.app.webserver.getHost()
self.url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['web_path'])
conv_config = {
'http_api': {
'api_tokens': [
'token-1',
'token-2',
'token-3',
],
'metric_store': 'metric_store',
}
}
conversation = yield self.app_helper.create_conversation(
config=conv_config)
yield self.app_helper.start_conversation(conversation)
self.conversation = yield self.app_helper.get_conversation(
conversation.key)
self.auth_headers = {
'Authorization': ['Basic ' + base64.b64encode('%s:%s' % (
conversation.user_account.key, 'token-1'))],
}
self.client = StreamingClient()
# Mock server to test HTTP posting of inbound messages & events
self.mock_push_server = MockHttpServer(self.handle_request)
yield self.mock_push_server.start()
self.add_cleanup(self.mock_push_server.stop)
self.push_calls = DeferredQueue()
self._setup_wait_for_request()
self.add_cleanup(self._wait_for_requests) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def track_wrapper(*args, **kw):
self._req_state['expected'] += 1
return orig_track(*args, **kw) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def _wait_for_requests(self):
while self._req_state['expected'] > 0:
yield self._req_state['queue'].get()
self._req_state['expected'] -= 1 | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def pull_message(self, count=1):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, messages.put, errors.put, url,
Headers(self.auth_headers))
received_messages = []
for msg_id in range(count):
yield self.app_helper.make_dispatch_inbound(
'in %s' % (msg_id,), message_id=str(msg_id),
conv=self.conversation)
recv_msg = yield messages.get()
received_messages.append(recv_msg)
receiver.disconnect()
returnValue((receiver, received_messages)) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_proxy_buffering_headers_off(self):
# This is the default, but we patch it anyway to make sure we're
# testing the right thing should the default change.
self.patch(StreamResourceMixin, 'proxy_buffering', False)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['no']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_proxy_buffering_headers_on(self):
self.patch(StreamResourceMixin, 'proxy_buffering', True)
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(headers.getRawHeaders('x-accel-buffering'), ['yes']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_content_type(self):
receiver, received_messages = yield self.pull_message()
headers = receiver._response.headers
self.assertEqual(
headers.getRawHeaders('content-type'),
['application/json; charset=utf-8']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_messages_stream(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
messages = DeferredQueue()
errors = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, messages.put, errors.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
msg2 = yield self.app_helper.make_dispatch_inbound(
'in 2', message_id='2', conv=self.conversation)
rm1 = yield messages.get()
rm2 = yield messages.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
rm1, rm2 = sorted([rm1, rm2], key=lambda m: m['message_id'])
self.assertEqual(msg1['message_id'], rm1['message_id'])
self.assertEqual(msg2['message_id'], rm2['message_id'])
self.assertEqual(errors.size, None) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_events_stream(self):
url = '%s/%s/events.json' % (self.url, self.conversation.key)
events = DeferredQueue()
errors = DeferredQueue()
receiver = yield self.client.stream(TransportEvent, events.put,
events.put, url,
Headers(self.auth_headers))
msg1 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 1', message_id='1')
ack1 = yield self.app_helper.make_dispatch_ack(
msg1, conv=self.conversation)
msg2 = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 2', message_id='2')
ack2 = yield self.app_helper.make_dispatch_ack(
msg2, conv=self.conversation)
ra1 = yield events.get()
ra2 = yield events.get()
receiver.disconnect()
# Sometimes messages arrive out of order if we're hitting real redis.
if ra1['event_id'] != ack1['event_id']:
ra1, ra2 = ra2, ra1
self.assertEqual(ack1['event_id'], ra1['event_id'])
self.assertEqual(ack2['event_id'], ra2['event_id'])
self.assertEqual(errors.size, None) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_missing_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_invalid_auth(self):
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
queue = DeferredQueue()
headers = Headers({
'Authorization': ['Basic %s' % (base64.b64encode('foo:bar'),)],
})
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url, headers)
response = yield receiver.get_response()
self.assertEqual(response.code, http.UNAUTHORIZED)
self.assertEqual(response.headers.getRawHeaders('www-authenticate'), [
'basic realm="Conversation Realm"']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_to(self):
msg = {
'to_addr': '+2345',
'content': 'foo',
'message_id': 'evil_id',
}
# TaggingMiddleware.add_tag_to_msg(msg, self.tag)
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
self.assertEqual(response.code, http.OK)
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], sent_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], msg['to_addr'])
self.assertEqual(sent_msg['from_addr'], None) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_to_within_content_length_limit(self):
self.conversation.config['http_api'].update({
'content_length_limit': 182,
})
yield self.conversation.save()
msg = {
'content': 'foo',
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], '+1234')
self.assertEqual(sent_msg['from_addr'], None) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_to_content_too_long(self):
self.conversation.config['http_api'].update({
'content_length_limit': 10,
})
yield self.conversation.save()
msg = {
'content': "This message is longer than 10 characters.",
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10") | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_to_with_evil_content(self):
msg = {
'content': 0xBAD,
'to_addr': '+1234',
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'") | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_to_with_evil_to_addr(self):
msg = {
'content': 'good',
'to_addr': 1234,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'to_addr'") | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292') | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to_within_content_length_limit(self):
self.conversation.config['http_api'].update({
'content_length_limit': 182,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
self.assertEqual(response.code, http.OK)
[sent_msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(sent_msg['to_addr'], put_msg['to_addr'])
self.assertEqual(sent_msg['helper_metadata'], {
'go': {
'conversation_key': self.conversation.key,
'conversation_type': 'http_api',
'user_account': self.conversation.user_account.key,
},
})
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['session_event'], None)
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292') | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to_content_too_long(self):
self.conversation.config['http_api'].update({
'content_length_limit': 10,
})
yield self.conversation.save()
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': "This message is longer than 10 characters.",
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(msg), self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Payload content too long: 42 > 10") | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to_with_evil_content(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 0xBAD,
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response, "Invalid or missing value for payload key 'content'") | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_invalid_in_reply_to(self):
msg = {
'content': 'foo',
'in_reply_to': '1', # this doesn't exist
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(response, 'Invalid in_reply_to value') | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_invalid_in_reply_to_with_missing_conversation_key(self):
# create a message with no conversation
inbound_msg = self.app_helper.make_inbound('in 1', message_id='msg-1')
vumi_api = self.app_helper.vumi_helper.get_vumi_api()
yield vumi_api.mdb.add_inbound_message(inbound_msg)
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
with LogCatcher(message='Invalid reply to message <Message .*>'
' which has no conversation key') as lc:
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
[error_log] = lc.messages()
self.assert_bad_request(response, "Invalid in_reply_to value")
self.assertTrue(inbound_msg['message_id'] in error_log) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to_with_evil_session_event(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'session_event': 0xBAD5E55104,
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assert_bad_request(
response,
"Invalid or missing value for payload key 'session_event'")
self.assertEqual(self.app_helper.get_dispatched_outbound(), []) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_in_reply_to_with_evil_message_id(self):
inbound_msg = yield self.app_helper.make_stored_inbound(
self.conversation, 'in 1', message_id='1')
msg = {
'content': 'foo',
'in_reply_to': inbound_msg['message_id'],
'message_id': 'evil_id'
}
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
response = yield http_request_full(url, json.dumps(msg),
self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
put_msg = json.loads(response.delivered_body)
[sent_msg] = self.app_helper.get_dispatched_outbound()
# We do not respect the message_id that's been given.
self.assertNotEqual(sent_msg['message_id'], msg['message_id'])
self.assertEqual(sent_msg['message_id'], put_msg['message_id'])
self.assertEqual(sent_msg['to_addr'], inbound_msg['from_addr'])
self.assertEqual(sent_msg['from_addr'], '9292') | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_metric_publishing(self):
metric_data = [
("vumi.test.v1", 1234, 'SUM'),
("vumi.test.v2", 3456, 'AVG'),
]
url = '%s/%s/metrics.json' % (self.url, self.conversation.key)
response = yield http_request_full(
url, json.dumps(metric_data), self.auth_headers, method='PUT')
self.assertEqual(response.code, http.OK)
self.assertEqual(
response.headers.getRawHeaders('content-type'),
['application/json; charset=utf-8'])
prefix = "go.campaigns.test-0-user.stores.metric_store"
self.assertEqual(
self.app_helper.get_published_metrics(self.app),
[("%s.vumi.test.v1" % prefix, 1234),
("%s.vumi.test.v2" % prefix, 3456)]) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_concurrency_limits(self):
config = yield self.app.get_config(None)
concurrency = config.concurrency_limit
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
max_receivers = [self.client.stream(
TransportUserMessage, queue.put, queue.put, url,
Headers(self.auth_headers)) for _ in range(concurrency)]
for i in range(concurrency):
msg = yield self.app_helper.make_dispatch_inbound(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
received = yield queue.get()
self.assertEqual(msg['message_id'], received['message_id'])
maxed_out_resp = yield http_request_full(
url, method='GET', headers=self.auth_headers)
self.assertEqual(maxed_out_resp.code, 403)
self.assertTrue(
'Too many concurrent connections' in maxed_out_resp.delivered_body)
[r.disconnect() for r in max_receivers] | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_disabling_concurrency_limit(self):
conv_resource = StreamingConversationResource(
self.app, self.conversation.key)
# negative concurrency limit disables it
ctxt = ConfigContext(user_account=self.conversation.user_account.key,
concurrency_limit=-1)
config = yield self.app.get_config(msg=None, ctxt=ctxt)
self.assertTrue(
(yield conv_resource.is_allowed(
config, self.conversation.user_account.key))) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_backlog_on_connect(self):
for i in range(10):
yield self.app_helper.make_dispatch_inbound(
'in %s' % (i,), message_id=str(i), conv=self.conversation)
queue = DeferredQueue()
url = '%s/%s/messages.json' % (self.url, self.conversation.key)
receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, url,
Headers(self.auth_headers))
for i in range(10):
received = yield queue.get()
self.assertEqual(received['message_id'], str(i))
receiver.disconnect() | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_health_response(self):
health_url = 'http://%s:%s%s' % (
self.addr.host, self.addr.port, self.config['health_path'])
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
yield self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
queue = DeferredQueue()
stream_url = '%s/%s/messages.json' % (self.url, self.conversation.key)
stream_receiver = self.client.stream(
TransportUserMessage, queue.put, queue.put, stream_url,
Headers(self.auth_headers))
yield queue.get()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '1')
stream_receiver.disconnect()
response = yield http_request_full(health_url, method='GET')
self.assertEqual(response.delivered_body, '0')
self.assertEqual(self.app.client_manager.clients, {
'sphex.stream.message.%s' % (self.conversation.key,): []
}) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_post_inbound_message(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
msg = yield msg_d
posted_msg = TransportUserMessage.from_json(posted_json_data)
self.assertEqual(posted_msg['message_id'], msg['message_id']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_post_inbound_message_201_response(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(201)
req.finish()
yield msg_d
self.assertEqual(lc.messages(), []) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_post_inbound_message_500_response(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_message_url': self.mock_push_server.url,
})
yield self.conversation.save()
with LogCatcher(message='Got unexpected response code') as lc:
msg_d = self.app_helper.make_dispatch_inbound(
'in 1', message_id='1', conv=self.conversation)
req = yield self.push_calls.get()
req.setResponseCode(500)
req.finish()
yield msg_d
[warning_log] = lc.messages()
self.assertTrue(self.mock_push_server.url in warning_log)
self.assertTrue('500' in warning_log) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_post_inbound_event(self):
# Set the URL so stuff is HTTP Posted instead of streamed.
self.conversation.config['http_api'].update({
'push_event_url': self.mock_push_server.url,
})
yield self.conversation.save()
msg = yield self.app_helper.make_stored_outbound(
self.conversation, 'out 1', message_id='1')
event_d = self.app_helper.make_dispatch_ack(
msg, conv=self.conversation)
req = yield self.push_calls.get()
posted_json_data = req.content.read()
req.finish()
ack = yield event_d
self.assertEqual(TransportEvent.from_json(posted_json_data), ack) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_bad_urls(self):
def assert_not_found(url, headers={}):
d = http_request_full(self.url, method='GET', headers=headers)
d.addCallback(lambda r: self.assertEqual(r.code, http.NOT_FOUND))
return d
yield assert_not_found(self.url)
yield assert_not_found(self.url + '/')
yield assert_not_found('%s/%s' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/' % (self.url, self.conversation.key),
headers=self.auth_headers)
yield assert_not_found('%s/%s/foo' % (self.url, self.conversation.key),
headers=self.auth_headers) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def test_send_message_command(self):
yield self.app_helper.dispatch_command(
'send_message',
user_account_key=self.conversation.user_account.key,
conversation_key=self.conversation.key,
command_data={
u'batch_id': u'batch-id',
u'content': u'foo',
u'to_addr': u'to_addr',
u'msg_options': {
u'helper_metadata': {
u'tag': {
u'tag': [u'longcode', u'default10080']
}
},
u'from_addr': u'default10080',
}
})
[msg] = self.app_helper.get_dispatched_outbound()
self.assertEqual(msg.payload['to_addr'], "to_addr")
self.assertEqual(msg.payload['from_addr'], "default10080")
self.assertEqual(msg.payload['content'], "foo")
self.assertEqual(msg.payload['message_type'], "user_message")
self.assertEqual(
msg.payload['helper_metadata']['go']['user_account'],
self.conversation.user_account.key)
self.assertEqual(
msg.payload['helper_metadata']['tag']['tag'],
['longcode', 'default10080']) | praekelt/vumi-go | [
15,
20,
15,
105,
1308905181
] |
def __init__(self):
super().__init__()
self.visited = [] | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!") | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def __init__(self):
super().__init__()
self.recorded_access_path = None | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def __init__(self):
super().__init__()
self.visited = [] | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def visit_BasicNodeReplacement(self, node):
self.visited.append("visited Copy!")
return node | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def __init__(self):
super().__init__()
self.recorded_access_path = None | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def visit_BasicNode(self, node):
return BasicNodeReplacement() | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def visit_BasicNodeReplacement(self, node):
return self.NONE_DEPUTY # Replace this node with None | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.visited, order) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingVisitor()
retval = visitor.visit(to_visit)
assert_equal(retval, None)
assert_equal(visitor.recorded_access_path, access_path) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_empty_transformer(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = EmptyTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_visit_order(self, node, order):
to_visit = self.load(node)
# The main stuff
visitor = VisitOrderCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(to_visit, retval)
assert_equal(visitor.visited, order) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_access_path(self, node, access):
to_visit = self.load(node)
access_path = self.load(access)
# The main stuff
visitor = AccessPathCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, to_visit)
assert_equal(visitor.recorded_access_path, access_path) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def test_transformation(self, node, expected):
to_visit = self.load(node)
expected_node = self.load(expected)
# The main stuff
visitor = TransformationCheckingTransformer()
retval = visitor.visit(to_visit)
assert_equal(retval, expected_node) | pradyunsg/Py2C | [
243,
76,
243,
3,
1379849666
] |
def __init__(self, **kwargs):
""" Initializes a Avatar instance
Notes:
You can specify all parameters while calling this methods.
A special argument named `data` will enable you to load the
object from a Python dictionary
Examples:
>>> avatar = NUAvatar(id=u'xxxx-xxx-xxx-xxx', name=u'Avatar')
>>> avatar = NUAvatar(data=my_dict)
"""
super(NUAvatar, self).__init__()
# Read/Write Attributes | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def last_updated_by(self):
""" Get last_updated_by value.
Notes:
ID of the user who last updated the object. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def last_updated_by(self, value):
""" Set last_updated_by value.
Notes:
ID of the user who last updated the object. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def last_updated_date(self):
""" Get last_updated_date value.
Notes:
Time stamp when this object was last updated. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def last_updated_date(self, value):
""" Set last_updated_date value.
Notes:
Time stamp when this object was last updated. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def embedded_metadata(self):
""" Get embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def embedded_metadata(self, value):
""" Set embedded_metadata value.
Notes:
Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def entity_scope(self):
""" Get entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def entity_scope(self, value):
""" Set entity_scope value.
Notes:
Specify if scope of entity is Data center or Enterprise level | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def creation_date(self):
""" Get creation_date value.
Notes:
Time stamp when this object was created. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def creation_date(self, value):
""" Set creation_date value.
Notes:
Time stamp when this object was created. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def owner(self):
""" Get owner value.
Notes:
Identifies the user that has created this object. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def owner(self, value):
""" Set owner value.
Notes:
Identifies the user that has created this object. | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def external_id(self):
""" Get external_id value.
Notes:
External object ID. Used for integration with third party systems | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def external_id(self, value):
""" Set external_id value.
Notes:
External object ID. Used for integration with third party systems | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def type(self):
""" Get type value.
Notes:
The image type | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def type(self, value):
""" Set type value.
Notes:
The image type | nuagenetworks/vspk-python | [
19,
18,
19,
7,
1457133058
] |
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance) | stephenlienharrell/roster-dns-management | [
1,
1,
1,
4,
1426209952
] |