body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
---|---|---|---|---|---|---|---|---|---|
d80262b0c54dc3dc8e43a4da1f24d04609db0336ec843802ef4b0871094f35e2 | @staticmethod
def validate(pixels: list[bytes]) -> tuple[(bool, str)]:
'Validates the image if ...\n 1. it has at least one pixel\n 2. all lines are the same length\n '
if (len(pixels) == 0):
return (False, 'has no pixels')
width = len(pixels[0])
for line in pixels:
if (len(line) != width):
return (False, 'line lengths are not uniform')
return (True, '') | Validates the image if ...
1. it has at least one pixel
2. all lines are the same length | tepra.py | validate | nnabeyang/tepra-lite-esp32 | 33 | python | @staticmethod
def validate(pixels: list[bytes]) -> tuple[(bool, str)]:
'Validates the image if ...\n 1. it has at least one pixel\n 2. all lines are the same length\n '
if (len(pixels) == 0):
return (False, 'has no pixels')
width = len(pixels[0])
for line in pixels:
if (len(line) != width):
return (False, 'line lengths are not uniform')
return (True, ) | @staticmethod
def validate(pixels: list[bytes]) -> tuple[(bool, str)]:
'Validates the image if ...\n 1. it has at least one pixel\n 2. all lines are the same length\n '
if (len(pixels) == 0):
return (False, 'has no pixels')
width = len(pixels[0])
for line in pixels:
if (len(line) != width):
return (False, 'line lengths are not uniform')
return (True, )<|docstring|>Validates the image if ...
1. it has at least one pixel
2. all lines are the same length<|endoftext|> |
c29091504765df384573fe92756c475b92aa0fb44e325bf6db48b722a985afc3 | @staticmethod
def validate_for_printing(pixels: list[bytes]) -> (bool, str):
'Validates the image if ...\n 1. it has at least 84 lines\n 2. all lines are 64 pixel length\n '
if (len(pixels) < 84):
return (False, 'has no enough lines')
for line in pixels:
if (len(line) != 8):
return (False, 'line lengths are not uniform')
return (True, '') | Validates the image if ...
1. it has at least 84 lines
2. all lines are 64 pixel length | tepra.py | validate_for_printing | nnabeyang/tepra-lite-esp32 | 33 | python | @staticmethod
def validate_for_printing(pixels: list[bytes]) -> (bool, str):
'Validates the image if ...\n 1. it has at least 84 lines\n 2. all lines are 64 pixel length\n '
if (len(pixels) < 84):
return (False, 'has no enough lines')
for line in pixels:
if (len(line) != 8):
return (False, 'line lengths are not uniform')
return (True, ) | @staticmethod
def validate_for_printing(pixels: list[bytes]) -> (bool, str):
'Validates the image if ...\n 1. it has at least 84 lines\n 2. all lines are 64 pixel length\n '
if (len(pixels) < 84):
return (False, 'has no enough lines')
for line in pixels:
if (len(line) != 8):
return (False, 'line lengths are not uniform')
return (True, )<|docstring|>Validates the image if ...
1. it has at least 84 lines
2. all lines are 64 pixel length<|endoftext|> |
c22eb9b02deb05ceaca7fde1f92f525287d848f3e0e12afd5cf69d1f522cac6c | def forward(self, q):
' Forward kinematic transform for the end effector. '
p = np.array([(((self.lx + q[0]) + (self.l1 * np.cos(q[1]))) + (self.l2 * np.cos((q[1] + q[2])))), ((self.ly + (self.l1 * np.sin(q[1]))) + (self.l2 * np.sin((q[1] + q[2])))), (q[1] + q[2])])
return p[self.output_idx] | Forward kinematic transform for the end effector. | mm2d/models/side.py | forward | adamheins/planar-playground | 0 | python | def forward(self, q):
' '
p = np.array([(((self.lx + q[0]) + (self.l1 * np.cos(q[1]))) + (self.l2 * np.cos((q[1] + q[2])))), ((self.ly + (self.l1 * np.sin(q[1]))) + (self.l2 * np.sin((q[1] + q[2])))), (q[1] + q[2])])
return p[self.output_idx] | def forward(self, q):
' '
p = np.array([(((self.lx + q[0]) + (self.l1 * np.cos(q[1]))) + (self.l2 * np.cos((q[1] + q[2])))), ((self.ly + (self.l1 * np.sin(q[1]))) + (self.l2 * np.sin((q[1] + q[2])))), (q[1] + q[2])])
return p[self.output_idx]<|docstring|>Forward kinematic transform for the end effector.<|endoftext|> |
9aed4e9eaa61d2f12089aebb9e64d561948f51ae87906cea11cf7efd746d295b | def jacobian(self, q):
' End effector Jacobian. '
J = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))], [0, 1, 1]])
return J[(self.output_idx, :)] | End effector Jacobian. | mm2d/models/side.py | jacobian | adamheins/planar-playground | 0 | python | def jacobian(self, q):
' '
J = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))], [0, 1, 1]])
return J[(self.output_idx, :)] | def jacobian(self, q):
' '
J = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))], [0, 1, 1]])
return J[(self.output_idx, :)]<|docstring|>End effector Jacobian.<|endoftext|> |
564b7680223bd5ef70cb03259d82f11d7262df21137e84fa4bd2269117696b76 | def dJdt(self, q, dq):
' Derivative of EE Jacobian w.r.t. time. '
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
J = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)], [0, 0, 0]])
return J[(self.output_idx, :)] | Derivative of EE Jacobian w.r.t. time. | mm2d/models/side.py | dJdt | adamheins/planar-playground | 0 | python | def dJdt(self, q, dq):
' '
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
J = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)], [0, 0, 0]])
return J[(self.output_idx, :)] | def dJdt(self, q, dq):
' '
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
J = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)], [0, 0, 0]])
return J[(self.output_idx, :)]<|docstring|>Derivative of EE Jacobian w.r.t. time.<|endoftext|> |
d30ba607c07a642ae1f20c51847d4d42aebe12cac60e790c9dbfcaed6701eb4c | def base_corners(self, q):
' Calculate the corners of the base of the robot. '
x0 = q[0]
y0 = 0
r = (self.bw * 0.5)
h = self.bh
x = np.array([(x0 - r), (x0 - r), (x0 + r), (x0 + r)])
y = np.array([y0, (y0 - h), (y0 - h), y0])
return (x, y) | Calculate the corners of the base of the robot. | mm2d/models/side.py | base_corners | adamheins/planar-playground | 0 | python | def base_corners(self, q):
' '
x0 = q[0]
y0 = 0
r = (self.bw * 0.5)
h = self.bh
x = np.array([(x0 - r), (x0 - r), (x0 + r), (x0 + r)])
y = np.array([y0, (y0 - h), (y0 - h), y0])
return (x, y) | def base_corners(self, q):
' '
x0 = q[0]
y0 = 0
r = (self.bw * 0.5)
h = self.bh
x = np.array([(x0 - r), (x0 - r), (x0 + r), (x0 + r)])
y = np.array([y0, (y0 - h), (y0 - h), y0])
return (x, y)<|docstring|>Calculate the corners of the base of the robot.<|endoftext|> |
84518d0e53507e16485a80279b4253c6b9fae9625a36564e9118754acdc6e845 | def arm_points(self, q):
' Calculate points on the arm. '
x0 = (q[0] + self.lx)
x1 = (x0 + (self.l1 * np.cos(q[1])))
x2 = (x1 + (self.l2 * np.cos((q[1] + q[2]))))
y0 = self.ly
y1 = (y0 + (self.l1 * np.sin(q[1])))
y2 = (y1 + (self.l2 * np.sin((q[1] + q[2]))))
x = np.array([x0, x1, x2])
y = np.array([y0, y1, y2])
return (x, y) | Calculate points on the arm. | mm2d/models/side.py | arm_points | adamheins/planar-playground | 0 | python | def arm_points(self, q):
' '
x0 = (q[0] + self.lx)
x1 = (x0 + (self.l1 * np.cos(q[1])))
x2 = (x1 + (self.l2 * np.cos((q[1] + q[2]))))
y0 = self.ly
y1 = (y0 + (self.l1 * np.sin(q[1])))
y2 = (y1 + (self.l2 * np.sin((q[1] + q[2]))))
x = np.array([x0, x1, x2])
y = np.array([y0, y1, y2])
return (x, y) | def arm_points(self, q):
' '
x0 = (q[0] + self.lx)
x1 = (x0 + (self.l1 * np.cos(q[1])))
x2 = (x1 + (self.l2 * np.cos((q[1] + q[2]))))
y0 = self.ly
y1 = (y0 + (self.l1 * np.sin(q[1])))
y2 = (y1 + (self.l2 * np.sin((q[1] + q[2]))))
x = np.array([x0, x1, x2])
y = np.array([y0, y1, y2])
return (x, y)<|docstring|>Calculate points on the arm.<|endoftext|> |
ae371c545c7eab0d1497a1256e0bac35e6b5139d71237a76a9c73a6cc7422a45 | def sample_points(self, q):
' Sample points across the robot body. '
(ax, ay) = self.arm_points(q)
ps = np.array([[(q[0] - 0.5), 0], [(q[0] + 0.5), 0], [q[0], 0], [ax[1], ay[1]], [ax[2], ay[2]]])
return ps | Sample points across the robot body. | mm2d/models/side.py | sample_points | adamheins/planar-playground | 0 | python | def sample_points(self, q):
' '
(ax, ay) = self.arm_points(q)
ps = np.array([[(q[0] - 0.5), 0], [(q[0] + 0.5), 0], [q[0], 0], [ax[1], ay[1]], [ax[2], ay[2]]])
return ps | def sample_points(self, q):
' '
(ax, ay) = self.arm_points(q)
ps = np.array([[(q[0] - 0.5), 0], [(q[0] + 0.5), 0], [q[0], 0], [ax[1], ay[1]], [ax[2], ay[2]]])
return ps<|docstring|>Sample points across the robot body.<|endoftext|> |
071f628958aa55cd52899d832eedf6b6163706cb42259bd47d5e9942ed212aff | def sample_jacobians(self, q):
' Jacobians of points sampled across the robot body. '
Js = np.zeros((5, 2, 3))
Js[(0, :, :)] = Js[(1, :, :)] = Js[(2, :, :)] = np.array([[1, 0, 0], [0, 0, 0]])
Js[(3, :, :)] = np.array([[1, ((- self.l1) * np.sin(q[1])), 0], [0, (self.l1 * np.cos(q[1])), 0]])
Js[(4, :, :)] = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))]])
return Js | Jacobians of points sampled across the robot body. | mm2d/models/side.py | sample_jacobians | adamheins/planar-playground | 0 | python | def sample_jacobians(self, q):
' '
Js = np.zeros((5, 2, 3))
Js[(0, :, :)] = Js[(1, :, :)] = Js[(2, :, :)] = np.array([[1, 0, 0], [0, 0, 0]])
Js[(3, :, :)] = np.array([[1, ((- self.l1) * np.sin(q[1])), 0], [0, (self.l1 * np.cos(q[1])), 0]])
Js[(4, :, :)] = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))]])
return Js | def sample_jacobians(self, q):
' '
Js = np.zeros((5, 2, 3))
Js[(0, :, :)] = Js[(1, :, :)] = Js[(2, :, :)] = np.array([[1, 0, 0], [0, 0, 0]])
Js[(3, :, :)] = np.array([[1, ((- self.l1) * np.sin(q[1])), 0], [0, (self.l1 * np.cos(q[1])), 0]])
Js[(4, :, :)] = np.array([[1, (((- self.l1) * np.sin(q[1])) - (self.l2 * np.sin((q[1] + q[2])))), ((- self.l2) * np.sin((q[1] + q[2])))], [0, ((self.l1 * np.cos(q[1])) + (self.l2 * np.cos((q[1] + q[2])))), (self.l2 * np.cos((q[1] + q[2])))]])
return Js<|docstring|>Jacobians of points sampled across the robot body.<|endoftext|> |
e0699f2fb224fe13237b17073a77f01fbf6c0cbefc1572aa84882d8fd3f320c8 | def sample_dJdt(self, q, dq):
' Time-derivative of Jacobians of points sampled across the robot\n body. '
dJs = np.zeros((5, 2, 3))
dJs[(3, :, :)] = np.array([[0, (((- self.l1) * np.cos(q[1])) * dq[1]), 0], [0, (((- self.l1) * np.sin(q[1])) * dq[1]), 0]])
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
dJs[(4, :, :)] = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)]])
return dJs | Time-derivative of Jacobians of points sampled across the robot
body. | mm2d/models/side.py | sample_dJdt | adamheins/planar-playground | 0 | python | def sample_dJdt(self, q, dq):
' Time-derivative of Jacobians of points sampled across the robot\n body. '
dJs = np.zeros((5, 2, 3))
dJs[(3, :, :)] = np.array([[0, (((- self.l1) * np.cos(q[1])) * dq[1]), 0], [0, (((- self.l1) * np.sin(q[1])) * dq[1]), 0]])
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
dJs[(4, :, :)] = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)]])
return dJs | def sample_dJdt(self, q, dq):
' Time-derivative of Jacobians of points sampled across the robot\n body. '
dJs = np.zeros((5, 2, 3))
dJs[(3, :, :)] = np.array([[0, (((- self.l1) * np.cos(q[1])) * dq[1]), 0], [0, (((- self.l1) * np.sin(q[1])) * dq[1]), 0]])
q12 = (q[1] + q[2])
dq12 = (dq[1] + dq[2])
dJs[(4, :, :)] = np.array([[0, ((((- self.l1) * np.cos(q[1])) * dq[1]) - ((self.l2 * np.cos(q12)) * dq12)), (((- self.l2) * np.cos(q12)) * dq12)], [0, ((((- self.l1) * np.sin(q[1])) * dq[1]) - ((self.l2 * np.sin(q12)) * dq12)), (((- self.l2) * np.sin(q12)) * dq12)]])
return dJs<|docstring|>Time-derivative of Jacobians of points sampled across the robot
body.<|endoftext|> |
599e7edf4cec0d2bceff1d412a0ffb60e2f0f5082cda9d6b4819c9e203cf5c90 | def mass_matrix(self, q):
' Compute dynamic mass matrix. '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
m11 = ((self.mb + self.m1) + self.m2)
m12 = ((((- ((0.5 * self.m1) + self.m2)) * self.l1) * np.sin(θ1)) - (((0.5 * self.m2) * self.l2) * np.sin(θ12)))
m13 = ((((- 0.5) * self.m2) * self.l2) * np.sin(θ12))
m22 = (((((((0.25 * self.m1) + self.m2) * (self.l1 ** 2)) + ((0.25 * self.m2) * (self.l2 ** 2))) + (((self.m2 * self.l1) * self.l2) * np.cos(θ2))) + self.I1) + self.I2)
m23 = ((((0.5 * self.m2) * self.l2) * ((0.5 * self.l2) + (self.l1 * np.cos(θ2)))) + self.I2)
m33 = (((0.25 * self.m2) * (self.l2 ** 2)) + self.I2)
return np.array([[m11, m12, m13], [m12, m22, m23], [m13, m23, m33]]) | Compute dynamic mass matrix. | mm2d/models/side.py | mass_matrix | adamheins/planar-playground | 0 | python | def mass_matrix(self, q):
' '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
m11 = ((self.mb + self.m1) + self.m2)
m12 = ((((- ((0.5 * self.m1) + self.m2)) * self.l1) * np.sin(θ1)) - (((0.5 * self.m2) * self.l2) * np.sin(θ12)))
m13 = ((((- 0.5) * self.m2) * self.l2) * np.sin(θ12))
m22 = (((((((0.25 * self.m1) + self.m2) * (self.l1 ** 2)) + ((0.25 * self.m2) * (self.l2 ** 2))) + (((self.m2 * self.l1) * self.l2) * np.cos(θ2))) + self.I1) + self.I2)
m23 = ((((0.5 * self.m2) * self.l2) * ((0.5 * self.l2) + (self.l1 * np.cos(θ2)))) + self.I2)
m33 = (((0.25 * self.m2) * (self.l2 ** 2)) + self.I2)
return np.array([[m11, m12, m13], [m12, m22, m23], [m13, m23, m33]]) | def mass_matrix(self, q):
' '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
m11 = ((self.mb + self.m1) + self.m2)
m12 = ((((- ((0.5 * self.m1) + self.m2)) * self.l1) * np.sin(θ1)) - (((0.5 * self.m2) * self.l2) * np.sin(θ12)))
m13 = ((((- 0.5) * self.m2) * self.l2) * np.sin(θ12))
m22 = (((((((0.25 * self.m1) + self.m2) * (self.l1 ** 2)) + ((0.25 * self.m2) * (self.l2 ** 2))) + (((self.m2 * self.l1) * self.l2) * np.cos(θ2))) + self.I1) + self.I2)
m23 = ((((0.5 * self.m2) * self.l2) * ((0.5 * self.l2) + (self.l1 * np.cos(θ2)))) + self.I2)
m33 = (((0.25 * self.m2) * (self.l2 ** 2)) + self.I2)
return np.array([[m11, m12, m13], [m12, m22, m23], [m13, m23, m33]])<|docstring|>Compute dynamic mass matrix.<|endoftext|> |
cf5d0c5be40ec6f3505dcc73a1cb674ba5a838efd2c20e1922078a03ab3bd8ff | def christoffel_matrix(self, q):
' Compute 3D matrix Γ of Christoffel symbols, as in the dynamic\n equations of motion:\n M @ ddq + dq @ Γ @ dq + g = τ.\n Note that C = dq @ Γ.\n '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
dMdxb = np.zeros((3, 3))
dMdθ1_12 = ((((((- 0.5) * self.m1) * self.l1) * np.cos(θ1)) - ((self.m2 * self.l1) * np.cos(θ1))) - (((0.5 * self.m2) * self.l2) * np.cos(θ12)))
dMdθ1_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ1 = np.array([[0, dMdθ1_12, dMdθ1_13], [dMdθ1_12, 0, 0], [dMdθ1_13, 0, 0]])
dMdθ2_12 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_22 = ((((- self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2_23 = (((((- 0.5) * self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2 = np.array([[0, dMdθ2_12, dMdθ2_13], [dMdθ2_12, dMdθ2_22, dMdθ2_23], [dMdθ2_13, dMdθ2_23, 0]])
dMdq = np.zeros((3, 3, 3))
dMdq[(:, :, 0)] = dMdxb
dMdq[(:, :, 1)] = dMdθ1
dMdq[(:, :, 2)] = dMdθ2
return (dMdq - (0.5 * dMdq.T)) | Compute 3D matrix Γ of Christoffel symbols, as in the dynamic
equations of motion:
M @ ddq + dq @ Γ @ dq + g = τ.
Note that C = dq @ Γ. | mm2d/models/side.py | christoffel_matrix | adamheins/planar-playground | 0 | python | def christoffel_matrix(self, q):
' Compute 3D matrix Γ of Christoffel symbols, as in the dynamic\n equations of motion:\n M @ ddq + dq @ Γ @ dq + g = τ.\n Note that C = dq @ Γ.\n '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
dMdxb = np.zeros((3, 3))
dMdθ1_12 = ((((((- 0.5) * self.m1) * self.l1) * np.cos(θ1)) - ((self.m2 * self.l1) * np.cos(θ1))) - (((0.5 * self.m2) * self.l2) * np.cos(θ12)))
dMdθ1_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ1 = np.array([[0, dMdθ1_12, dMdθ1_13], [dMdθ1_12, 0, 0], [dMdθ1_13, 0, 0]])
dMdθ2_12 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_22 = ((((- self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2_23 = (((((- 0.5) * self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2 = np.array([[0, dMdθ2_12, dMdθ2_13], [dMdθ2_12, dMdθ2_22, dMdθ2_23], [dMdθ2_13, dMdθ2_23, 0]])
dMdq = np.zeros((3, 3, 3))
dMdq[(:, :, 0)] = dMdxb
dMdq[(:, :, 1)] = dMdθ1
dMdq[(:, :, 2)] = dMdθ2
return (dMdq - (0.5 * dMdq.T)) | def christoffel_matrix(self, q):
' Compute 3D matrix Γ of Christoffel symbols, as in the dynamic\n equations of motion:\n M @ ddq + dq @ Γ @ dq + g = τ.\n Note that C = dq @ Γ.\n '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
dMdxb = np.zeros((3, 3))
dMdθ1_12 = ((((((- 0.5) * self.m1) * self.l1) * np.cos(θ1)) - ((self.m2 * self.l1) * np.cos(θ1))) - (((0.5 * self.m2) * self.l2) * np.cos(θ12)))
dMdθ1_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ1 = np.array([[0, dMdθ1_12, dMdθ1_13], [dMdθ1_12, 0, 0], [dMdθ1_13, 0, 0]])
dMdθ2_12 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_13 = ((((- 0.5) * self.m2) * self.l2) * np.cos(θ12))
dMdθ2_22 = ((((- self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2_23 = (((((- 0.5) * self.m2) * self.l1) * self.l2) * np.sin(θ2))
dMdθ2 = np.array([[0, dMdθ2_12, dMdθ2_13], [dMdθ2_12, dMdθ2_22, dMdθ2_23], [dMdθ2_13, dMdθ2_23, 0]])
dMdq = np.zeros((3, 3, 3))
dMdq[(:, :, 0)] = dMdxb
dMdq[(:, :, 1)] = dMdθ1
dMdq[(:, :, 2)] = dMdθ2
return (dMdq - (0.5 * dMdq.T))<|docstring|>Compute 3D matrix Γ of Christoffel symbols, as in the dynamic
equations of motion:
M @ ddq + dq @ Γ @ dq + g = τ.
Note that C = dq @ Γ.<|endoftext|> |
e3db66409ec66a5260133f8f3b1bba848d3cf2019677f12d6c4deb74f65b1657 | def gravity_vector(self, q):
' Calculate the gravity vector. '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
return np.array([0, ((((((0.5 * self.m1) + self.m2) * self.gravity) * self.l1) * np.cos(θ1)) + ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))), ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))]) | Calculate the gravity vector. | mm2d/models/side.py | gravity_vector | adamheins/planar-playground | 0 | python | def gravity_vector(self, q):
' '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
return np.array([0, ((((((0.5 * self.m1) + self.m2) * self.gravity) * self.l1) * np.cos(θ1)) + ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))), ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))]) | def gravity_vector(self, q):
' '
(xb, θ1, θ2) = q
θ12 = (θ1 + θ2)
return np.array([0, ((((((0.5 * self.m1) + self.m2) * self.gravity) * self.l1) * np.cos(θ1)) + ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))), ((((0.5 * self.m2) * self.l2) * self.gravity) * np.cos(θ12))])<|docstring|>Calculate the gravity vector.<|endoftext|> |
b6d4f9067d8814f893fa6a4c7db8665f13ad73782cf5ceec8f8cb81b9eb59c4e | def calc_torque(self, q, dq, ddq):
' Calculate the required torque for the given joint positions,\n velocity, and accelerations. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
return (((M @ ddq) + ((dq @ Γ) @ dq)) + g) | Calculate the required torque for the given joint positions,
velocity, and accelerations. | mm2d/models/side.py | calc_torque | adamheins/planar-playground | 0 | python | def calc_torque(self, q, dq, ddq):
' Calculate the required torque for the given joint positions,\n velocity, and accelerations. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
return (((M @ ddq) + ((dq @ Γ) @ dq)) + g) | def calc_torque(self, q, dq, ddq):
' Calculate the required torque for the given joint positions,\n velocity, and accelerations. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
return (((M @ ddq) + ((dq @ Γ) @ dq)) + g)<|docstring|>Calculate the required torque for the given joint positions,
velocity, and accelerations.<|endoftext|> |
11240b0aecd983fda241c256b0c544bdbaba14b034c1414663d17a4618a34903 | def command_torque(self, q, dq, tau, dt):
' Calculate the new state [q, dq] from current state [q, dq] and\n torque input tau. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
ddq = np.linalg.solve(M, ((tau - ((dq @ Γ) @ dq)) - g))
q = (q + (dt * dq))
dq = (dq + (dt * ddq))
return (q, dq) | Calculate the new state [q, dq] from current state [q, dq] and
torque input tau. | mm2d/models/side.py | command_torque | adamheins/planar-playground | 0 | python | def command_torque(self, q, dq, tau, dt):
' Calculate the new state [q, dq] from current state [q, dq] and\n torque input tau. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
ddq = np.linalg.solve(M, ((tau - ((dq @ Γ) @ dq)) - g))
q = (q + (dt * dq))
dq = (dq + (dt * ddq))
return (q, dq) | def command_torque(self, q, dq, tau, dt):
' Calculate the new state [q, dq] from current state [q, dq] and\n torque input tau. '
M = self.mass_matrix(q)
Γ = self.christoffel_matrix(q)
g = self.gravity_vector(q)
ddq = np.linalg.solve(M, ((tau - ((dq @ Γ) @ dq)) - g))
q = (q + (dt * dq))
dq = (dq + (dt * ddq))
return (q, dq)<|docstring|>Calculate the new state [q, dq] from current state [q, dq] and
torque input tau.<|endoftext|> |
79309ab91b554be99ce0a0427eeaf28be62b71c429306ede94c0cceaee7168a8 | def step(self, q, u, dt, dq_last=None):
' Step forward one timestep. '
dq = bound_array(u, (- self.vel_lim), self.vel_lim)
if (dq_last is not None):
dq = bound_array(dq, (((- self.acc_lim) * dt) + dq_last), ((self.acc_lim * dt) + dq_last))
q = (q + (dt * dq))
return (q, dq) | Step forward one timestep. | mm2d/models/side.py | step | adamheins/planar-playground | 0 | python | def step(self, q, u, dt, dq_last=None):
' '
dq = bound_array(u, (- self.vel_lim), self.vel_lim)
if (dq_last is not None):
dq = bound_array(dq, (((- self.acc_lim) * dt) + dq_last), ((self.acc_lim * dt) + dq_last))
q = (q + (dt * dq))
return (q, dq) | def step(self, q, u, dt, dq_last=None):
' '
dq = bound_array(u, (- self.vel_lim), self.vel_lim)
if (dq_last is not None):
dq = bound_array(dq, (((- self.acc_lim) * dt) + dq_last), ((self.acc_lim * dt) + dq_last))
q = (q + (dt * dq))
return (q, dq)<|docstring|>Step forward one timestep.<|endoftext|> |
742542dafaf1537eb9c5686f33f0a72c3b0a7001d29e6040c9d77992fb24e291 | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n '
lazy_import()
return {'class_id': (str,), 'object_type': (str,), 'daily_limit': (int,), 'snapshot_expiry_time': (str,), 'array': (StoragePureArrayRelationship,), 'protection_group': (StoragePureProtectionGroupRelationship,), 'registered_device': (AssetDeviceRegistrationRelationship,)} | This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type. | intersight/model/storage_pure_snapshot_schedule_all_of.py | openapi_types | CiscoDevNet/intersight-python | 5 | python | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n '
lazy_import()
return {'class_id': (str,), 'object_type': (str,), 'daily_limit': (int,), 'snapshot_expiry_time': (str,), 'array': (StoragePureArrayRelationship,), 'protection_group': (StoragePureProtectionGroupRelationship,), 'registered_device': (AssetDeviceRegistrationRelationship,)} | @cached_property
def openapi_types():
'\n This must be a method because a model may have properties that are\n of type self, this must run after the class is loaded\n\n Returns\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n '
lazy_import()
return {'class_id': (str,), 'object_type': (str,), 'daily_limit': (int,), 'snapshot_expiry_time': (str,), 'array': (StoragePureArrayRelationship,), 'protection_group': (StoragePureProtectionGroupRelationship,), 'registered_device': (AssetDeviceRegistrationRelationship,)}<|docstring|>This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.<|endoftext|> |
7b29a683f37a9bf8230f5b27dbf6b1f9f1d948ecf7bdecd809de5173cf32d541 | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'StoragePureSnapshotScheduleAllOf - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the \'ClassId\' property.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _spec_property_naming (bool): True if the variable names in the input data\n are serialized names, as specified in the OpenAPI document.\n False if the variable names in the input data\n are pythonic names, e.g. snake case (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n _visited_composed_classes (tuple): This stores a tuple of\n classes that we have traveled through so that\n if we see that class again we will not use its\n discriminator again.\n When traveling through a discriminator, the\n composed schema that is\n is traveled through is added to this set.\n For example if Animal has a discriminator\n petType and we pass in "Dog", and the class Dog\n allOf includes Animal, we move through Animal\n once using the discriminator, and pick Dog.\n Then in Dog, we will make an instance of the\n Animal class but this time we won\'t travel\n through its discriminator because we passed in\n _visited_composed_classes = (Animal,)\n daily_limit (int): Total number of snapshots per day to be available on source above and over the specified retention time. PureStorage FlashArray maintains all created snapshot until retention period. Daily limit is applied only on the snapshots once retention time is expired. In case of, daily limit is less than the number of snapshot available on source, system select snapshots evenly spaced out throughout the day.. [optional] # noqa: E501\n snapshot_expiry_time (str): Duration to keep the daily limit snapshots on source array. StorageArray deletes the snapshots permanently from source beyond this period.. [optional] # noqa: E501\n array (StoragePureArrayRelationship): [optional] # noqa: E501\n protection_group (StoragePureProtectionGroupRelationship): [optional] # noqa: E501\n registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501\n '
class_id = kwargs.get('class_id', 'storage.PureSnapshotSchedule')
object_type = kwargs.get('object_type', 'storage.PureSnapshotSchedule')
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(('Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.' % (args, self.__class__.__name__)), path_to_item=_path_to_item, valid_classes=(self.__class__,))
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = (_visited_composed_classes + (self.__class__,))
self.class_id = class_id
self.object_type = object_type
for (var_name, var_value) in kwargs.items():
if ((var_name not in self.attribute_map) and (self._configuration is not None) and self._configuration.discard_unknown_keys and (self.additional_properties_type is None)):
continue
setattr(self, var_name, var_value) | StoragePureSnapshotScheduleAllOf - a model defined in OpenAPI
Args:
Keyword Args:
class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501
object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
daily_limit (int): Total number of snapshots per day to be available on source above and over the specified retention time. PureStorage FlashArray maintains all created snapshot until retention period. Daily limit is applied only on the snapshots once retention time is expired. In case of, daily limit is less than the number of snapshot available on source, system select snapshots evenly spaced out throughout the day.. [optional] # noqa: E501
snapshot_expiry_time (str): Duration to keep the daily limit snapshots on source array. StorageArray deletes the snapshots permanently from source beyond this period.. [optional] # noqa: E501
array (StoragePureArrayRelationship): [optional] # noqa: E501
protection_group (StoragePureProtectionGroupRelationship): [optional] # noqa: E501
registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501 | intersight/model/storage_pure_snapshot_schedule_all_of.py | __init__ | CiscoDevNet/intersight-python | 5 | python | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'StoragePureSnapshotScheduleAllOf - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the \'ClassId\' property.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _spec_property_naming (bool): True if the variable names in the input data\n are serialized names, as specified in the OpenAPI document.\n False if the variable names in the input data\n are pythonic names, e.g. snake case (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n _visited_composed_classes (tuple): This stores a tuple of\n classes that we have traveled through so that\n if we see that class again we will not use its\n discriminator again.\n When traveling through a discriminator, the\n composed schema that is\n is traveled through is added to this set.\n For example if Animal has a discriminator\n petType and we pass in "Dog", and the class Dog\n allOf includes Animal, we move through Animal\n once using the discriminator, and pick Dog.\n Then in Dog, we will make an instance of the\n Animal class but this time we won\'t travel\n through its discriminator because we passed in\n _visited_composed_classes = (Animal,)\n daily_limit (int): Total number of snapshots per day to be available on source above and over the specified retention time. PureStorage FlashArray maintains all created snapshot until retention period. Daily limit is applied only on the snapshots once retention time is expired. In case of, daily limit is less than the number of snapshot available on source, system select snapshots evenly spaced out throughout the day.. [optional] # noqa: E501\n snapshot_expiry_time (str): Duration to keep the daily limit snapshots on source array. StorageArray deletes the snapshots permanently from source beyond this period.. [optional] # noqa: E501\n array (StoragePureArrayRelationship): [optional] # noqa: E501\n protection_group (StoragePureProtectionGroupRelationship): [optional] # noqa: E501\n registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501\n '
class_id = kwargs.get('class_id', 'storage.PureSnapshotSchedule')
object_type = kwargs.get('object_type', 'storage.PureSnapshotSchedule')
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(('Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.' % (args, self.__class__.__name__)), path_to_item=_path_to_item, valid_classes=(self.__class__,))
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = (_visited_composed_classes + (self.__class__,))
self.class_id = class_id
self.object_type = object_type
for (var_name, var_value) in kwargs.items():
if ((var_name not in self.attribute_map) and (self._configuration is not None) and self._configuration.discard_unknown_keys and (self.additional_properties_type is None)):
continue
setattr(self, var_name, var_value) | @convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
'StoragePureSnapshotScheduleAllOf - a model defined in OpenAPI\n\n Args:\n\n Keyword Args:\n class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the \'ClassId\' property.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501\n _check_type (bool): if True, values for parameters in openapi_types\n will be type checked and a TypeError will be\n raised if the wrong type is input.\n Defaults to True\n _path_to_item (tuple/list): This is a list of keys or values to\n drill down to the model in received_data\n when deserializing a response\n _spec_property_naming (bool): True if the variable names in the input data\n are serialized names, as specified in the OpenAPI document.\n False if the variable names in the input data\n are pythonic names, e.g. snake case (default)\n _configuration (Configuration): the instance to use when\n deserializing a file_type parameter.\n If passed, type conversion is attempted\n If omitted no type conversion is done.\n _visited_composed_classes (tuple): This stores a tuple of\n classes that we have traveled through so that\n if we see that class again we will not use its\n discriminator again.\n When traveling through a discriminator, the\n composed schema that is\n is traveled through is added to this set.\n For example if Animal has a discriminator\n petType and we pass in "Dog", and the class Dog\n allOf includes Animal, we move through Animal\n once using the discriminator, and pick Dog.\n Then in Dog, we will make an instance of the\n Animal class but this time we won\'t travel\n through its discriminator because we passed in\n _visited_composed_classes = (Animal,)\n daily_limit (int): Total number of snapshots per day to be available on source above and over the specified retention time. PureStorage FlashArray maintains all created snapshot until retention period. Daily limit is applied only on the snapshots once retention time is expired. In case of, daily limit is less than the number of snapshot available on source, system select snapshots evenly spaced out throughout the day.. [optional] # noqa: E501\n snapshot_expiry_time (str): Duration to keep the daily limit snapshots on source array. StorageArray deletes the snapshots permanently from source beyond this period.. [optional] # noqa: E501\n array (StoragePureArrayRelationship): [optional] # noqa: E501\n protection_group (StoragePureProtectionGroupRelationship): [optional] # noqa: E501\n registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501\n '
class_id = kwargs.get('class_id', 'storage.PureSnapshotSchedule')
object_type = kwargs.get('object_type', 'storage.PureSnapshotSchedule')
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(('Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments.' % (args, self.__class__.__name__)), path_to_item=_path_to_item, valid_classes=(self.__class__,))
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = (_visited_composed_classes + (self.__class__,))
self.class_id = class_id
self.object_type = object_type
for (var_name, var_value) in kwargs.items():
if ((var_name not in self.attribute_map) and (self._configuration is not None) and self._configuration.discard_unknown_keys and (self.additional_properties_type is None)):
continue
setattr(self, var_name, var_value)<|docstring|>StoragePureSnapshotScheduleAllOf - a model defined in OpenAPI
Args:
Keyword Args:
class_id (str): The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501
object_type (str): The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property.. defaults to "storage.PureSnapshotSchedule", must be one of ["storage.PureSnapshotSchedule", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
daily_limit (int): Total number of snapshots per day to be available on source above and over the specified retention time. PureStorage FlashArray maintains all created snapshot until retention period. Daily limit is applied only on the snapshots once retention time is expired. In case of, daily limit is less than the number of snapshot available on source, system select snapshots evenly spaced out throughout the day.. [optional] # noqa: E501
snapshot_expiry_time (str): Duration to keep the daily limit snapshots on source array. StorageArray deletes the snapshots permanently from source beyond this period.. [optional] # noqa: E501
array (StoragePureArrayRelationship): [optional] # noqa: E501
protection_group (StoragePureProtectionGroupRelationship): [optional] # noqa: E501
registered_device (AssetDeviceRegistrationRelationship): [optional] # noqa: E501<|endoftext|> |
84c66e4d9f1e5c93cee21a7944a7691e9f7983009fc95ee3a7480eb636e707a4 | def get_status():
'Returns the status of the elastic cluster'
es = get_elasticsearch()
try:
cluster_health = es.cluster.health()
except ConnectionError as err:
logging.getLogger(__name__).error('Failed to connect to ES: %s', err)
cluster_health = {}
es_reachable = False
else:
es_reachable = True
es_cluster_health = (cluster_health.get('status') in ES_RUNNING_STATUS)
ready = es_cluster_health
return {'es': {'reachable': es_reachable, 'running': es_cluster_health}, 'ready': ready} | Returns the status of the elastic cluster | idunn/api/status.py | get_status | QwantResearch/idunn | 26 | python | def get_status():
es = get_elasticsearch()
try:
cluster_health = es.cluster.health()
except ConnectionError as err:
logging.getLogger(__name__).error('Failed to connect to ES: %s', err)
cluster_health = {}
es_reachable = False
else:
es_reachable = True
es_cluster_health = (cluster_health.get('status') in ES_RUNNING_STATUS)
ready = es_cluster_health
return {'es': {'reachable': es_reachable, 'running': es_cluster_health}, 'ready': ready} | def get_status():
es = get_elasticsearch()
try:
cluster_health = es.cluster.health()
except ConnectionError as err:
logging.getLogger(__name__).error('Failed to connect to ES: %s', err)
cluster_health = {}
es_reachable = False
else:
es_reachable = True
es_cluster_health = (cluster_health.get('status') in ES_RUNNING_STATUS)
ready = es_cluster_health
return {'es': {'reachable': es_reachable, 'running': es_cluster_health}, 'ready': ready}<|docstring|>Returns the status of the elastic cluster<|endoftext|> |
3f6063dc5205a7996a54cef9b8e1d0938227a9c6cd349dbc38636b3da324a869 | def save_blog(self):
'\n Function that saves blogs\n '
db.session.add(self)
db.session.commit() | Function that saves blogs | app/models.py | save_blog | elkwal/Blog_App | 0 | python | def save_blog(self):
'\n \n '
db.session.add(self)
db.session.commit() | def save_blog(self):
'\n \n '
db.session.add(self)
db.session.commit()<|docstring|>Function that saves blogs<|endoftext|> |
0798945d4da175ebca3bc542f84598ac70478f715245f4b136ac0701d7978d8d | @classmethod
def get_all_blogs(cls):
'\n Function that queries the databse and returns all the blogs\n '
blogs = Blog.query.all()
return blogs | Function that queries the databse and returns all the blogs | app/models.py | get_all_blogs | elkwal/Blog_App | 0 | python | @classmethod
def get_all_blogs(cls):
'\n \n '
blogs = Blog.query.all()
return blogs | @classmethod
def get_all_blogs(cls):
'\n \n '
blogs = Blog.query.all()
return blogs<|docstring|>Function that queries the databse and returns all the blogs<|endoftext|> |
d730c71b24de06c01728bdad44a58b8869420211690b8f6bd5a00c1b1a99bb4b | @classmethod
def get_blogs_by_category(cls, cat_id):
'\n Function that queries the databse and returns blogs based on the\n category passed to it\n '
return blog.query.filter_by(category_id=cat_id) | Function that queries the databse and returns blogs based on the
category passed to it | app/models.py | get_blogs_by_category | elkwal/Blog_App | 0 | python | @classmethod
def get_blogs_by_category(cls, cat_id):
'\n Function that queries the databse and returns blogs based on the\n category passed to it\n '
return blog.query.filter_by(category_id=cat_id) | @classmethod
def get_blogs_by_category(cls, cat_id):
'\n Function that queries the databse and returns blogs based on the\n category passed to it\n '
return blog.query.filter_by(category_id=cat_id)<|docstring|>Function that queries the databse and returns blogs based on the
category passed to it<|endoftext|> |
53735cc887571526be244cb35ccb6779e0a31d41b7ad213b6b8b770417db476a | def save_comment(self):
'\n Function that saves comments\n '
db.session.add(self)
db.session.commit() | Function that saves comments | app/models.py | save_comment | elkwal/Blog_App | 0 | python | def save_comment(self):
'\n \n '
db.session.add(self)
db.session.commit() | def save_comment(self):
'\n \n '
db.session.add(self)
db.session.commit()<|docstring|>Function that saves comments<|endoftext|> |
3565a945940879b9da93fc877a2950798062164abe769f0c0e436115205e907b | @classmethod
def get_categories(cls):
'\n This function fetches all the categories from the database\n '
categories = BlogCategory.query.all()
return categories | This function fetches all the categories from the database | app/models.py | get_categories | elkwal/Blog_App | 0 | python | @classmethod
def get_categories(cls):
'\n \n '
categories = BlogCategory.query.all()
return categories | @classmethod
def get_categories(cls):
'\n \n '
categories = BlogCategory.query.all()
return categories<|docstring|>This function fetches all the categories from the database<|endoftext|> |
0e3490644ad9c12d5649c4aa6da4ea281af66f12f9208a55c9c088e03e6272de | def _check_altspec(spec):
'\n Confirms that specified alternative `spec` is valid (space, density) format\n\n Parameters\n ----------\n spec : (2,) tuple-of-str\n Where entries are (space, density) of desired target space\n\n Returns\n -------\n spec : (2,) tuple-of-str\n Unmodified input `spec`\n\n Raises\n ------\n ValueError\n If `spec` is not valid format\n '
invalid_spec = ((spec is None) or (len(spec) != 2))
if (not invalid_spec):
(space, den) = spec
space = ALIAS.get(space, space)
valid = DENSITIES.get(space)
invalid_spec = ((valid is None) or (den not in valid))
if invalid_spec:
raise ValueError(f'Must provide valid alternative specification of format (space, density). Received: {spec}')
return (space, den) | Confirms that specified alternative `spec` is valid (space, density) format
Parameters
----------
spec : (2,) tuple-of-str
Where entries are (space, density) of desired target space
Returns
-------
spec : (2,) tuple-of-str
Unmodified input `spec`
Raises
------
ValueError
If `spec` is not valid format | neuromaps/resampling.py | _check_altspec | VinceBaz/neuromaps | 0 | python | def _check_altspec(spec):
'\n Confirms that specified alternative `spec` is valid (space, density) format\n\n Parameters\n ----------\n spec : (2,) tuple-of-str\n Where entries are (space, density) of desired target space\n\n Returns\n -------\n spec : (2,) tuple-of-str\n Unmodified input `spec`\n\n Raises\n ------\n ValueError\n If `spec` is not valid format\n '
invalid_spec = ((spec is None) or (len(spec) != 2))
if (not invalid_spec):
(space, den) = spec
space = ALIAS.get(space, space)
valid = DENSITIES.get(space)
invalid_spec = ((valid is None) or (den not in valid))
if invalid_spec:
raise ValueError(f'Must provide valid alternative specification of format (space, density). Received: {spec}')
return (space, den) | def _check_altspec(spec):
'\n Confirms that specified alternative `spec` is valid (space, density) format\n\n Parameters\n ----------\n spec : (2,) tuple-of-str\n Where entries are (space, density) of desired target space\n\n Returns\n -------\n spec : (2,) tuple-of-str\n Unmodified input `spec`\n\n Raises\n ------\n ValueError\n If `spec` is not valid format\n '
invalid_spec = ((spec is None) or (len(spec) != 2))
if (not invalid_spec):
(space, den) = spec
space = ALIAS.get(space, space)
valid = DENSITIES.get(space)
invalid_spec = ((valid is None) or (den not in valid))
if invalid_spec:
raise ValueError(f'Must provide valid alternative specification of format (space, density). Received: {spec}')
return (space, den)<|docstring|>Confirms that specified alternative `spec` is valid (space, density) format
Parameters
----------
spec : (2,) tuple-of-str
Where entries are (space, density) of desired target space
Returns
-------
spec : (2,) tuple-of-str
Unmodified input `spec`
Raises
------
ValueError
If `spec` is not valid format<|endoftext|> |
4173745358299762af73686077febb4eaadaf9e4d2c8e646c8f4da8a97922165 | def check(self, replacements, apply_latency, latency, delta):
'\n Check if it is really waiting for function call, when latency is enabled\n '
envs = f'{ENV_STORAGE_FILE}={self.storage_file} {ENV_REPLACEMENT_FILE}={DATA_DIR}/{replacements} {ENV_APPLY_LATENCY}={apply_latency}'
cmd = f"bash -c '{envs} {self.test_command}'"
print(cmd)
self.assertFalse(os.path.exists(self.storage_file))
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
print(open(self.storage_file).readlines())
self.assertTrue(os.path.exists(self.storage_file))
self.assertAlmostEqual(2, (after - before), delta=delta)
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
self.assertAlmostEqual(latency, (after - before), delta=delta) | Check if it is really waiting for function call, when latency is enabled | tests/test_e2e_test_patching.py | check | FrNecas/requre | 4 | python | def check(self, replacements, apply_latency, latency, delta):
'\n \n '
envs = f'{ENV_STORAGE_FILE}={self.storage_file} {ENV_REPLACEMENT_FILE}={DATA_DIR}/{replacements} {ENV_APPLY_LATENCY}={apply_latency}'
cmd = f"bash -c '{envs} {self.test_command}'"
print(cmd)
self.assertFalse(os.path.exists(self.storage_file))
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
print(open(self.storage_file).readlines())
self.assertTrue(os.path.exists(self.storage_file))
self.assertAlmostEqual(2, (after - before), delta=delta)
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
self.assertAlmostEqual(latency, (after - before), delta=delta) | def check(self, replacements, apply_latency, latency, delta):
'\n \n '
envs = f'{ENV_STORAGE_FILE}={self.storage_file} {ENV_REPLACEMENT_FILE}={DATA_DIR}/{replacements} {ENV_APPLY_LATENCY}={apply_latency}'
cmd = f"bash -c '{envs} {self.test_command}'"
print(cmd)
self.assertFalse(os.path.exists(self.storage_file))
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
print(open(self.storage_file).readlines())
self.assertTrue(os.path.exists(self.storage_file))
self.assertAlmostEqual(2, (after - before), delta=delta)
before = time.time()
run_command(cmd=cmd, output=True)
after = time.time()
self.assertAlmostEqual(latency, (after - before), delta=delta)<|docstring|>Check if it is really waiting for function call, when latency is enabled<|endoftext|> |
4fde3012f358fb21455e8bde61d2fb126e357c8aa16dda4626da7a33d932240a | @classmethod
def parse_ifconfig(cls, ifconfig_output: str) -> List[InterfaceInfo]:
'\n enx000ec6c0c623: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n ether 00:0e:c0:c0:56:23 txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1000 (Local Loopback)\n RX packets 1134271 bytes 1046040386 (1.0 GB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 1134271 bytes 1046040386 (1.0 GB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n '
iface_info_list: List[InterfaceInfo] = list()
out = ifconfig_output.replace('\n\n', '\n')
list_blocks = re.split('\n[a-zA-Z0-9]', out)
for block in list_blocks:
if (('inet ' not in block) or ('loop ' in block)):
continue
iface_name = re.search('(\\S+):', block).groups()[0]
iface_ip = re.search('inet (\\S+) ', block).groups()[0].replace('addr:', '')
if (iface_ip == '127.0.0.1'):
continue
iface_info_list.append(InterfaceInfo(iface_name, iface_ip))
return iface_info_list | enx000ec6c0c623: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether 00:0e:c0:c0:56:23 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 1134271 bytes 1046040386 (1.0 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1134271 bytes 1046040386 (1.0 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 | src/hervenue/parser/parse.py | parse_ifconfig | jsrdzhk/hervenue | 0 | python | @classmethod
def parse_ifconfig(cls, ifconfig_output: str) -> List[InterfaceInfo]:
'\n enx000ec6c0c623: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n ether 00:0e:c0:c0:56:23 txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1000 (Local Loopback)\n RX packets 1134271 bytes 1046040386 (1.0 GB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 1134271 bytes 1046040386 (1.0 GB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n '
iface_info_list: List[InterfaceInfo] = list()
out = ifconfig_output.replace('\n\n', '\n')
list_blocks = re.split('\n[a-zA-Z0-9]', out)
for block in list_blocks:
if (('inet ' not in block) or ('loop ' in block)):
continue
iface_name = re.search('(\\S+):', block).groups()[0]
iface_ip = re.search('inet (\\S+) ', block).groups()[0].replace('addr:', )
if (iface_ip == '127.0.0.1'):
continue
iface_info_list.append(InterfaceInfo(iface_name, iface_ip))
return iface_info_list | @classmethod
def parse_ifconfig(cls, ifconfig_output: str) -> List[InterfaceInfo]:
'\n enx000ec6c0c623: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500\n ether 00:0e:c0:c0:56:23 txqueuelen 1000 (Ethernet)\n RX packets 0 bytes 0 (0.0 B)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 0 bytes 0 (0.0 B)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536\n inet 127.0.0.1 netmask 255.0.0.0\n inet6 ::1 prefixlen 128 scopeid 0x10<host>\n loop txqueuelen 1000 (Local Loopback)\n RX packets 1134271 bytes 1046040386 (1.0 GB)\n RX errors 0 dropped 0 overruns 0 frame 0\n TX packets 1134271 bytes 1046040386 (1.0 GB)\n TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0\n '
iface_info_list: List[InterfaceInfo] = list()
out = ifconfig_output.replace('\n\n', '\n')
list_blocks = re.split('\n[a-zA-Z0-9]', out)
for block in list_blocks:
if (('inet ' not in block) or ('loop ' in block)):
continue
iface_name = re.search('(\\S+):', block).groups()[0]
iface_ip = re.search('inet (\\S+) ', block).groups()[0].replace('addr:', )
if (iface_ip == '127.0.0.1'):
continue
iface_info_list.append(InterfaceInfo(iface_name, iface_ip))
return iface_info_list<|docstring|>enx000ec6c0c623: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether 00:0e:c0:c0:56:23 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 1134271 bytes 1046040386 (1.0 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1134271 bytes 1046040386 (1.0 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0<|endoftext|> |
dd21ebcbfe986f7c0b4efaff429a0b093fa4629e8375ce3339e33a0c368c972a | def create_test_users(self):
'\n Override creation of test users\n '
User = get_user_model()
self.admin = milkman.deliver(User, email='[email protected]', is_superuser=True)
self.user = milkman.deliver(User, email='[email protected]')
self.user2 = milkman.deliver(User, email='[email protected]') | Override creation of test users | appengine/src/greenday_api/tests/test_user_api.py | create_test_users | meedan/montage | 6 | python | def create_test_users(self):
'\n \n '
User = get_user_model()
self.admin = milkman.deliver(User, email='[email protected]', is_superuser=True)
self.user = milkman.deliver(User, email='[email protected]')
self.user2 = milkman.deliver(User, email='[email protected]') | def create_test_users(self):
'\n \n '
User = get_user_model()
self.admin = milkman.deliver(User, email='[email protected]', is_superuser=True)
self.user = milkman.deliver(User, email='[email protected]')
self.user2 = milkman.deliver(User, email='[email protected]')<|docstring|>Override creation of test users<|endoftext|> |
293e81fccc111c6ae35c5137456c5cc82f8aac17d99a4470d762a2e50a59f434 | def test_filter_users(self):
' Test that the correct users are returned when doing partial filters\n on the first_name, last_name and email fields\n '
User = get_user_model()
charlie_brown = milkman.deliver(User, first_name='Charlie', last_name='Brown', email='[email protected]')
charlie_brooker = milkman.deliver(User, first_name='Charlie', last_name='Brooker', email='[email protected]')
someone_brooker = milkman.deliver(User, first_name='Someone', last_name='Brooker', email='[email protected]')
def _check_filtered_users(q, *users):
self._sign_in(self.admin)
response = self.api.users_filter(UserFilterContainer.combined_message_class(q=q))
self.assertIsInstance(response, UserListResponse)
items_pks = [item.id for item in response.items]
self.assertEqual(len(users), len(items_pks))
for user in users:
self.assertTrue((user.pk in items_pks))
with self.assertNumQueries(2):
_check_filtered_users('example', charlie_brown, charlie_brooker, someone_brooker, self.user, self.user2)
with self.assertNumQueries(2):
_check_filtered_users('charlie', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('charl', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('brooker', charlie_brooker, someone_brooker)
with self.assertNumQueries(2):
_check_filtered_users('someone', someone_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brooker', charlie_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brown', charlie_brown)
with self.assertNumQueries(3):
_check_filtered_users('Someone Brown')
self._sign_out()
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_filter, UserFilterContainer.combined_message_class(q=None)) | Test that the correct users are returned when doing partial filters
on the first_name, last_name and email fields | appengine/src/greenday_api/tests/test_user_api.py | test_filter_users | meedan/montage | 6 | python | def test_filter_users(self):
' Test that the correct users are returned when doing partial filters\n on the first_name, last_name and email fields\n '
User = get_user_model()
charlie_brown = milkman.deliver(User, first_name='Charlie', last_name='Brown', email='[email protected]')
charlie_brooker = milkman.deliver(User, first_name='Charlie', last_name='Brooker', email='[email protected]')
someone_brooker = milkman.deliver(User, first_name='Someone', last_name='Brooker', email='[email protected]')
def _check_filtered_users(q, *users):
self._sign_in(self.admin)
response = self.api.users_filter(UserFilterContainer.combined_message_class(q=q))
self.assertIsInstance(response, UserListResponse)
items_pks = [item.id for item in response.items]
self.assertEqual(len(users), len(items_pks))
for user in users:
self.assertTrue((user.pk in items_pks))
with self.assertNumQueries(2):
_check_filtered_users('example', charlie_brown, charlie_brooker, someone_brooker, self.user, self.user2)
with self.assertNumQueries(2):
_check_filtered_users('charlie', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('charl', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('brooker', charlie_brooker, someone_brooker)
with self.assertNumQueries(2):
_check_filtered_users('someone', someone_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brooker', charlie_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brown', charlie_brown)
with self.assertNumQueries(3):
_check_filtered_users('Someone Brown')
self._sign_out()
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_filter, UserFilterContainer.combined_message_class(q=None)) | def test_filter_users(self):
' Test that the correct users are returned when doing partial filters\n on the first_name, last_name and email fields\n '
User = get_user_model()
charlie_brown = milkman.deliver(User, first_name='Charlie', last_name='Brown', email='[email protected]')
charlie_brooker = milkman.deliver(User, first_name='Charlie', last_name='Brooker', email='[email protected]')
someone_brooker = milkman.deliver(User, first_name='Someone', last_name='Brooker', email='[email protected]')
def _check_filtered_users(q, *users):
self._sign_in(self.admin)
response = self.api.users_filter(UserFilterContainer.combined_message_class(q=q))
self.assertIsInstance(response, UserListResponse)
items_pks = [item.id for item in response.items]
self.assertEqual(len(users), len(items_pks))
for user in users:
self.assertTrue((user.pk in items_pks))
with self.assertNumQueries(2):
_check_filtered_users('example', charlie_brown, charlie_brooker, someone_brooker, self.user, self.user2)
with self.assertNumQueries(2):
_check_filtered_users('charlie', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('charl', charlie_brown, charlie_brooker)
with self.assertNumQueries(2):
_check_filtered_users('brooker', charlie_brooker, someone_brooker)
with self.assertNumQueries(2):
_check_filtered_users('someone', someone_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brooker', charlie_brooker)
with self.assertNumQueries(3):
_check_filtered_users('Charlie Brown', charlie_brown)
with self.assertNumQueries(3):
_check_filtered_users('Someone Brown')
self._sign_out()
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_filter, UserFilterContainer.combined_message_class(q=None))<|docstring|>Test that the correct users are returned when doing partial filters
on the first_name, last_name and email fields<|endoftext|> |
47cbfbc7c2ddb460585608b9d09dade84a9b6c468ec74fc23d2af995be400c98 | def test_create_user(self):
'\n Create a new user\n '
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]'))
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERCREATED, object_id=True), self.assertNumQueries(6):
response = self.api.users_create(UserCreateContainer.combined_message_class(email='[email protected]'))
self.assertIsInstance(response, UserResponseMessage)
new_user = get_user_model().objects.get(email='[email protected]')
self.assertEqual(new_user.pk, response.id)
project = milkman.deliver(Project)
project.set_owner(self.user)
project.add_admin(self.user2, pending=False)
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]')) | Create a new user | appengine/src/greenday_api/tests/test_user_api.py | test_create_user | meedan/montage | 6 | python | def test_create_user(self):
'\n \n '
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]'))
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERCREATED, object_id=True), self.assertNumQueries(6):
response = self.api.users_create(UserCreateContainer.combined_message_class(email='[email protected]'))
self.assertIsInstance(response, UserResponseMessage)
new_user = get_user_model().objects.get(email='[email protected]')
self.assertEqual(new_user.pk, response.id)
project = milkman.deliver(Project)
project.set_owner(self.user)
project.add_admin(self.user2, pending=False)
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]')) | def test_create_user(self):
'\n \n '
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]'))
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERCREATED, object_id=True), self.assertNumQueries(6):
response = self.api.users_create(UserCreateContainer.combined_message_class(email='[email protected]'))
self.assertIsInstance(response, UserResponseMessage)
new_user = get_user_model().objects.get(email='[email protected]')
self.assertEqual(new_user.pk, response.id)
project = milkman.deliver(Project)
project.set_owner(self.user)
project.add_admin(self.user2, pending=False)
self._sign_in(self.user)
self.assertRaises(ForbiddenException, self.api.users_create, UserCreateContainer.combined_message_class(email='[email protected]'))<|docstring|>Create a new user<|endoftext|> |
f8f63b187cf8129e6e758a5f6aa41b7df5970ee29b21d8669be4c9bdc5620303 | def test_update_user(self):
"\n Update a user's profile\n "
user = get_user_model().objects.create(username='123', email='[email protected]', is_active=False)
request = UserUpdateContainer.combined_message_class(id=user.id, first_name='foo', last_name='bar', email='[email protected]', is_superuser=True, is_staff=True, profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True, is_active=True)
self._sign_in(user)
self.assertRaises(ForbiddenException, self.api.users_update, request)
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERUPDATED, object_id=user.pk), self.assertNumQueries(4):
response = self.api.users_update(request)
self.assertIsInstance(response, UserResponseMessage)
user = get_user_model().objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.is_superuser, response.is_superuser)
self.assertEqual(user.is_staff, response.is_staff)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
self.assertEqual(user.is_active, response.is_active) | Update a user's profile | appengine/src/greenday_api/tests/test_user_api.py | test_update_user | meedan/montage | 6 | python | def test_update_user(self):
"\n \n "
user = get_user_model().objects.create(username='123', email='[email protected]', is_active=False)
request = UserUpdateContainer.combined_message_class(id=user.id, first_name='foo', last_name='bar', email='[email protected]', is_superuser=True, is_staff=True, profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True, is_active=True)
self._sign_in(user)
self.assertRaises(ForbiddenException, self.api.users_update, request)
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERUPDATED, object_id=user.pk), self.assertNumQueries(4):
response = self.api.users_update(request)
self.assertIsInstance(response, UserResponseMessage)
user = get_user_model().objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.is_superuser, response.is_superuser)
self.assertEqual(user.is_staff, response.is_staff)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
self.assertEqual(user.is_active, response.is_active) | def test_update_user(self):
"\n \n "
user = get_user_model().objects.create(username='123', email='[email protected]', is_active=False)
request = UserUpdateContainer.combined_message_class(id=user.id, first_name='foo', last_name='bar', email='[email protected]', is_superuser=True, is_staff=True, profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True, is_active=True)
self._sign_in(user)
self.assertRaises(ForbiddenException, self.api.users_update, request)
self._sign_in(self.admin)
with self.assertEventRecorded(EventKind.USERUPDATED, object_id=user.pk), self.assertNumQueries(4):
response = self.api.users_update(request)
self.assertIsInstance(response, UserResponseMessage)
user = get_user_model().objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.is_superuser, response.is_superuser)
self.assertEqual(user.is_staff, response.is_staff)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)
self.assertEqual(user.is_active, response.is_active)<|docstring|>Update a user's profile<|endoftext|> |
0e16e128f3f59c49bd860008089eb411c53c52c7a78328d40cd2ef2d6427d4ba | def test_update_current_user(self):
"\n Update the currently logged in user's profile\n "
User = get_user_model()
user = User.objects.create(username='123', email='[email protected]', is_active=False)
self._sign_in(user)
request = CurrentUserUpdateContainer.combined_message_class(first_name='foo', last_name='bar', email='[email protected]', profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True)
with self.assertNumQueries(2):
response = self.api.update_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
user = User.objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda) | Update the currently logged in user's profile | appengine/src/greenday_api/tests/test_user_api.py | test_update_current_user | meedan/montage | 6 | python | def test_update_current_user(self):
"\n \n "
User = get_user_model()
user = User.objects.create(username='123', email='[email protected]', is_active=False)
self._sign_in(user)
request = CurrentUserUpdateContainer.combined_message_class(first_name='foo', last_name='bar', email='[email protected]', profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True)
with self.assertNumQueries(2):
response = self.api.update_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
user = User.objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda) | def test_update_current_user(self):
"\n \n "
User = get_user_model()
user = User.objects.create(username='123', email='[email protected]', is_active=False)
self._sign_in(user)
request = CurrentUserUpdateContainer.combined_message_class(first_name='foo', last_name='bar', email='[email protected]', profile_img_url='http://example.com/a.jpg', google_plus_profile='http://plus.google.com/foobar', accepted_nda=True)
with self.assertNumQueries(2):
response = self.api.update_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
user = User.objects.get(pk=user.pk)
self.assertEqual(user.pk, response.id)
self.assertEqual(user.email, request.email)
self.assertEqual(user.first_name, response.first_name)
self.assertEqual(user.last_name, response.last_name)
self.assertEqual(user.profile_img_url, response.profile_img_url)
self.assertEqual(user.google_plus_profile, response.google_plus_profile)
self.assertEqual(user.accepted_nda, response.accepted_nda)<|docstring|>Update the currently logged in user's profile<|endoftext|> |
f93d31ad1b148b05e28da96b0e8e13452d7f1fa5143db2f30e8d9198ec86bed3 | @mock.patch('greenday_api.user.user_api.defer_delete_user')
def test_delete_self(self, mock_defer_delete_user):
'\n User deleting themselves\n '
self._sign_in(self.user)
self.api.delete_current_user(message_types.VoidMessage())
mock_defer_delete_user.called_once_with(self.user, self.user) | User deleting themselves | appengine/src/greenday_api/tests/test_user_api.py | test_delete_self | meedan/montage | 6 | python | @mock.patch('greenday_api.user.user_api.defer_delete_user')
def test_delete_self(self, mock_defer_delete_user):
'\n \n '
self._sign_in(self.user)
self.api.delete_current_user(message_types.VoidMessage())
mock_defer_delete_user.called_once_with(self.user, self.user) | @mock.patch('greenday_api.user.user_api.defer_delete_user')
def test_delete_self(self, mock_defer_delete_user):
'\n \n '
self._sign_in(self.user)
self.api.delete_current_user(message_types.VoidMessage())
mock_defer_delete_user.called_once_with(self.user, self.user)<|docstring|>User deleting themselves<|endoftext|> |
7a1a15d58582fb4093164e7e771384dea97f3af60066c22b23c2e4cac5df8545 | def test_get_current_user(self):
'\n Get the current logged in user\n '
self._sign_in(self.user)
request = message_types.VoidMessage()
with self.assertNumQueries(1):
response = self.api.get_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
self.assertEqual(self.user.pk, response.id) | Get the current logged in user | appengine/src/greenday_api/tests/test_user_api.py | test_get_current_user | meedan/montage | 6 | python | def test_get_current_user(self):
'\n \n '
self._sign_in(self.user)
request = message_types.VoidMessage()
with self.assertNumQueries(1):
response = self.api.get_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
self.assertEqual(self.user.pk, response.id) | def test_get_current_user(self):
'\n \n '
self._sign_in(self.user)
request = message_types.VoidMessage()
with self.assertNumQueries(1):
response = self.api.get_current_user(request)
self.assertIsInstance(response, UserResponseMessage)
self.assertEqual(self.user.pk, response.id)<|docstring|>Get the current logged in user<|endoftext|> |
688b7e041f2f765fec8758e69e1fb80ccf8ed75af98ad4418ea9553b9a544332 | def setUp(self):
'\n Bootstrap test data\n '
super(UserAPIStatsTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(owner=self.admin)
self.globaltag = milkman.deliver(GlobalTag, name='tag2', description='buzz', image_url='img.jpg')
self.projecttag = ProjectTag.add_root(project=self.project, global_tag=self.globaltag)
self.videotag = VideoTag.objects.create(project=self.project, project_tag=self.projecttag, video=self.video)
self.videotaginstance = VideoTagInstance.objects.create(video_tag=self.videotag, user=self.user) | Bootstrap test data | appengine/src/greenday_api/tests/test_user_api.py | setUp | meedan/montage | 6 | python | def setUp(self):
'\n \n '
super(UserAPIStatsTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(owner=self.admin)
self.globaltag = milkman.deliver(GlobalTag, name='tag2', description='buzz', image_url='img.jpg')
self.projecttag = ProjectTag.add_root(project=self.project, global_tag=self.globaltag)
self.videotag = VideoTag.objects.create(project=self.project, project_tag=self.projecttag, video=self.video)
self.videotaginstance = VideoTagInstance.objects.create(video_tag=self.videotag, user=self.user) | def setUp(self):
'\n \n '
super(UserAPIStatsTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(owner=self.admin)
self.globaltag = milkman.deliver(GlobalTag, name='tag2', description='buzz', image_url='img.jpg')
self.projecttag = ProjectTag.add_root(project=self.project, global_tag=self.globaltag)
self.videotag = VideoTag.objects.create(project=self.project, project_tag=self.projecttag, video=self.video)
self.videotaginstance = VideoTagInstance.objects.create(video_tag=self.videotag, user=self.user)<|docstring|>Bootstrap test data<|endoftext|> |
ca81bb79f710ec8b9d75616d59d06971cfb70bb9e0f843d0a72c4ff706d93af5 | def test_get_self_stats(self):
"\n Get current user's statistics\n "
self._sign_in(self.user)
UserVideoDetail.objects.create(user=self.user, video=self.video, watched=True)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user.pk)
self.assertEqual(response.videos_watched, 1)
self.assertEqual(response.tags_added, 1) | Get current user's statistics | appengine/src/greenday_api/tests/test_user_api.py | test_get_self_stats | meedan/montage | 6 | python | def test_get_self_stats(self):
"\n \n "
self._sign_in(self.user)
UserVideoDetail.objects.create(user=self.user, video=self.video, watched=True)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user.pk)
self.assertEqual(response.videos_watched, 1)
self.assertEqual(response.tags_added, 1) | def test_get_self_stats(self):
"\n \n "
self._sign_in(self.user)
UserVideoDetail.objects.create(user=self.user, video=self.video, watched=True)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user.pk)
self.assertEqual(response.videos_watched, 1)
self.assertEqual(response.tags_added, 1)<|docstring|>Get current user's statistics<|endoftext|> |
d2f48525fcbdc225196ce38b0de5fd3a4d9006f3446b06add31165030e49888f | def test_get_self_stats_no_data(self):
"\n Get current user's statistics - no stats available\n "
self._sign_in(self.user2)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user2.pk)
self.assertEqual(response.videos_watched, 0)
self.assertEqual(response.tags_added, 0) | Get current user's statistics - no stats available | appengine/src/greenday_api/tests/test_user_api.py | test_get_self_stats_no_data | meedan/montage | 6 | python | def test_get_self_stats_no_data(self):
"\n \n "
self._sign_in(self.user2)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user2.pk)
self.assertEqual(response.videos_watched, 0)
self.assertEqual(response.tags_added, 0) | def test_get_self_stats_no_data(self):
"\n \n "
self._sign_in(self.user2)
with self.assertNumQueries(3):
response = self.api.get_current_user_stats(message_types.VoidMessage())
self.assertEqual(response.id, self.user2.pk)
self.assertEqual(response.videos_watched, 0)
self.assertEqual(response.tags_added, 0)<|docstring|>Get current user's statistics - no stats available<|endoftext|> |
9f7c5af5b8e1bed740f9fa9f256a84853e6219de16c1c50968da67cff41c0aff | @staticmethod
def ssh(spec):
'\n\n name: name of the job\n host: host on which we execute\n os: if true use os.system, this uses a temporary file, so be careful\n if false use subprocess.check_output\n stderr: result of stderror\n stdout: result of stdout\n returncode: 0 is success\n success: Ture if successfull e.g. returncode == 0\n status: a status: defined, running, done, failed\n\n :param spec:\n :return:\n '
spec = dotdict(spec)
hostname = os.uname()[1]
local = (hostname == spec.host)
if ('key' not in spec):
spec.key = path_expand('~/.ssh/id_rsa.pub')
ssh = f'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i {spec.key} {spec.host}'
if ('os' in spec):
if ('tmp' not in spec):
spec.tmp = '/tmp'
tee = f'tee {spec.tmp}/cloudmesh.{spec.name}'
if local:
command = f'{spec.command} | {tee}'
else:
command = f'{ssh} {spec.command} | {tee}'
returncode = os.system(command)
result = readfile(f'{spec.tmp}/cloudmesh.{spec.name}').strip()
else:
if local:
command = f'{spec.command} '
else:
command = f"{ssh} '{spec.command}'"
try:
result = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as grepexc:
print('Error Code', grepexc.returncode, grepexc.output)
result = f'Command could not run | Error Code: {grepexc.returncode}'
result = result.encode('UTF-8')
returncode = 0
return dict({'name': spec.name, 'stdout': result, 'stderr': '', 'returncode': returncode, 'status': 'defined'}) | name: name of the job
host: host on which we execute
os: if true use os.system, this uses a temporary file, so be careful
if false use subprocess.check_output
stderr: result of stderror
stdout: result of stdout
returncode: 0 is success
success: Ture if successfull e.g. returncode == 0
status: a status: defined, running, done, failed
:param spec:
:return: | cloudmesh/common/JobSet.py | ssh | eriklarsolson/cloudmesh-common | 0 | python | @staticmethod
def ssh(spec):
'\n\n name: name of the job\n host: host on which we execute\n os: if true use os.system, this uses a temporary file, so be careful\n if false use subprocess.check_output\n stderr: result of stderror\n stdout: result of stdout\n returncode: 0 is success\n success: Ture if successfull e.g. returncode == 0\n status: a status: defined, running, done, failed\n\n :param spec:\n :return:\n '
spec = dotdict(spec)
hostname = os.uname()[1]
local = (hostname == spec.host)
if ('key' not in spec):
spec.key = path_expand('~/.ssh/id_rsa.pub')
ssh = f'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i {spec.key} {spec.host}'
if ('os' in spec):
if ('tmp' not in spec):
spec.tmp = '/tmp'
tee = f'tee {spec.tmp}/cloudmesh.{spec.name}'
if local:
command = f'{spec.command} | {tee}'
else:
command = f'{ssh} {spec.command} | {tee}'
returncode = os.system(command)
result = readfile(f'{spec.tmp}/cloudmesh.{spec.name}').strip()
else:
if local:
command = f'{spec.command} '
else:
command = f"{ssh} '{spec.command}'"
try:
result = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as grepexc:
print('Error Code', grepexc.returncode, grepexc.output)
result = f'Command could not run | Error Code: {grepexc.returncode}'
result = result.encode('UTF-8')
returncode = 0
return dict({'name': spec.name, 'stdout': result, 'stderr': , 'returncode': returncode, 'status': 'defined'}) | @staticmethod
def ssh(spec):
'\n\n name: name of the job\n host: host on which we execute\n os: if true use os.system, this uses a temporary file, so be careful\n if false use subprocess.check_output\n stderr: result of stderror\n stdout: result of stdout\n returncode: 0 is success\n success: Ture if successfull e.g. returncode == 0\n status: a status: defined, running, done, failed\n\n :param spec:\n :return:\n '
spec = dotdict(spec)
hostname = os.uname()[1]
local = (hostname == spec.host)
if ('key' not in spec):
spec.key = path_expand('~/.ssh/id_rsa.pub')
ssh = f'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i {spec.key} {spec.host}'
if ('os' in spec):
if ('tmp' not in spec):
spec.tmp = '/tmp'
tee = f'tee {spec.tmp}/cloudmesh.{spec.name}'
if local:
command = f'{spec.command} | {tee}'
else:
command = f'{ssh} {spec.command} | {tee}'
returncode = os.system(command)
result = readfile(f'{spec.tmp}/cloudmesh.{spec.name}').strip()
else:
if local:
command = f'{spec.command} '
else:
command = f"{ssh} '{spec.command}'"
try:
result = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as grepexc:
print('Error Code', grepexc.returncode, grepexc.output)
result = f'Command could not run | Error Code: {grepexc.returncode}'
result = result.encode('UTF-8')
returncode = 0
return dict({'name': spec.name, 'stdout': result, 'stderr': , 'returncode': returncode, 'status': 'defined'})<|docstring|>name: name of the job
host: host on which we execute
os: if true use os.system, this uses a temporary file, so be careful
if false use subprocess.check_output
stderr: result of stderror
stdout: result of stdout
returncode: 0 is success
success: Ture if successfull e.g. returncode == 0
status: a status: defined, running, done, failed
:param spec:
:return:<|endoftext|> |
ce7b8d4c73dd2077898688cf8d15f46c979d460cbb9b8d33e551c105241eee0e | def _make_fake_real_user():
'Make a User whose profile.fake_user is False'
user = SocialProfileFactory.create().user
UserSocialAuthFactory.create(user=user, provider=BACKEND_MITX_ONLINE)
user.profile.fake_user = False
user.profile.save()
now = now_in_utc()
UserCacheRefreshTimeFactory.create(user=user, enrollment=now, certificate=now, current_grade=now)
return user | Make a User whose profile.fake_user is False | dashboard/api_test.py | _make_fake_real_user | mitodl/micromasters | 32 | python | def _make_fake_real_user():
user = SocialProfileFactory.create().user
UserSocialAuthFactory.create(user=user, provider=BACKEND_MITX_ONLINE)
user.profile.fake_user = False
user.profile.save()
now = now_in_utc()
UserCacheRefreshTimeFactory.create(user=user, enrollment=now, certificate=now, current_grade=now)
return user | def _make_fake_real_user():
user = SocialProfileFactory.create().user
UserSocialAuthFactory.create(user=user, provider=BACKEND_MITX_ONLINE)
user.profile.fake_user = False
user.profile.save()
now = now_in_utc()
UserCacheRefreshTimeFactory.create(user=user, enrollment=now, certificate=now, current_grade=now)
return user<|docstring|>Make a User whose profile.fake_user is False<|endoftext|> |
c00233a73183e4016a168ae8fb4e678128fbc91c72fc948af340e8f0efc7c693 | @pytest.fixture
def users_without_with_cache(db):
'Create users with an empty cache'
up_to_date = [_make_fake_real_user() for _ in range(5)]
needs_update = [_make_fake_real_user() for _ in range(5)]
for user in needs_update:
user.usercacherefreshtime.delete()
return (needs_update, up_to_date) | Create users with an empty cache | dashboard/api_test.py | users_without_with_cache | mitodl/micromasters | 32 | python | @pytest.fixture
def users_without_with_cache(db):
up_to_date = [_make_fake_real_user() for _ in range(5)]
needs_update = [_make_fake_real_user() for _ in range(5)]
for user in needs_update:
user.usercacherefreshtime.delete()
return (needs_update, up_to_date) | @pytest.fixture
def users_without_with_cache(db):
up_to_date = [_make_fake_real_user() for _ in range(5)]
needs_update = [_make_fake_real_user() for _ in range(5)]
for user in needs_update:
user.usercacherefreshtime.delete()
return (needs_update, up_to_date)<|docstring|>Create users with an empty cache<|endoftext|> |
dfe653f7302677b8bc2e4d1fd2eb83659518f29d7573dc45cce4861ff0041464 | @pytest.fixture
def patched_redis_keys(mocker):
'Patch redis cache keys'
mocker.patch('dashboard.api.CACHE_KEY_FAILED_USERS_NOT_TO_UPDATE', TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE)
mocker.patch('dashboard.api.CACHE_KEY_FAILURE_NUMS_BY_USER', TEST_CACHE_KEY_FAILURES_BY_USER)
(yield)
con = get_redis_connection('redis')
con.delete(TEST_CACHE_KEY_FAILURES_BY_USER)
con.delete(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE) | Patch redis cache keys | dashboard/api_test.py | patched_redis_keys | mitodl/micromasters | 32 | python | @pytest.fixture
def patched_redis_keys(mocker):
mocker.patch('dashboard.api.CACHE_KEY_FAILED_USERS_NOT_TO_UPDATE', TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE)
mocker.patch('dashboard.api.CACHE_KEY_FAILURE_NUMS_BY_USER', TEST_CACHE_KEY_FAILURES_BY_USER)
(yield)
con = get_redis_connection('redis')
con.delete(TEST_CACHE_KEY_FAILURES_BY_USER)
con.delete(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE) | @pytest.fixture
def patched_redis_keys(mocker):
mocker.patch('dashboard.api.CACHE_KEY_FAILED_USERS_NOT_TO_UPDATE', TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE)
mocker.patch('dashboard.api.CACHE_KEY_FAILURE_NUMS_BY_USER', TEST_CACHE_KEY_FAILURES_BY_USER)
(yield)
con = get_redis_connection('redis')
con.delete(TEST_CACHE_KEY_FAILURES_BY_USER)
con.delete(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE)<|docstring|>Patch redis cache keys<|endoftext|> |
47881c7c36f9758deaa4a160f892e4092a51f1af0f4817ef04d07a1316a65218 | def test_calculate_up_to_date(users_without_with_cache):
'\n calculate_users_to_refresh should return a list of user ids\n for users whose cache has expired or who are not cached\n '
(needs_update, _) = users_without_with_cache
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update])) | calculate_users_to_refresh should return a list of user ids
for users whose cache has expired or who are not cached | dashboard/api_test.py | test_calculate_up_to_date | mitodl/micromasters | 32 | python | def test_calculate_up_to_date(users_without_with_cache):
'\n calculate_users_to_refresh should return a list of user ids\n for users whose cache has expired or who are not cached\n '
(needs_update, _) = users_without_with_cache
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update])) | def test_calculate_up_to_date(users_without_with_cache):
'\n calculate_users_to_refresh should return a list of user ids\n for users whose cache has expired or who are not cached\n '
(needs_update, _) = users_without_with_cache
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update]))<|docstring|>calculate_users_to_refresh should return a list of user ids
for users whose cache has expired or who are not cached<|endoftext|> |
6d15c959f3106d3a53a810a9ebba46c8c267a266a6bd64e1694586a0c4965cfd | def test_calculate_missing_cache(users_without_with_cache):
"\n If a user's cache is missing they should be part of the list of users to update\n "
(needs_update, up_to_date) = users_without_with_cache
up_to_date[0].usercacherefreshtime.delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted(([user.id for user in needs_update] + [up_to_date[0].id]))) | If a user's cache is missing they should be part of the list of users to update | dashboard/api_test.py | test_calculate_missing_cache | mitodl/micromasters | 32 | python | def test_calculate_missing_cache(users_without_with_cache):
"\n \n "
(needs_update, up_to_date) = users_without_with_cache
up_to_date[0].usercacherefreshtime.delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted(([user.id for user in needs_update] + [up_to_date[0].id]))) | def test_calculate_missing_cache(users_without_with_cache):
"\n \n "
(needs_update, up_to_date) = users_without_with_cache
up_to_date[0].usercacherefreshtime.delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted(([user.id for user in needs_update] + [up_to_date[0].id])))<|docstring|>If a user's cache is missing they should be part of the list of users to update<|endoftext|> |
914ef732f92abc98edd8fe23dcd60923a1f024586354674d2c9cf0570df11030 | def test_calculate_fake_user(users_without_with_cache):
'Fake users should not have their caches updated'
(needs_update, _) = users_without_with_cache
needs_update[0].profile.fake_user = True
needs_update[0].profile.save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | Fake users should not have their caches updated | dashboard/api_test.py | test_calculate_fake_user | mitodl/micromasters | 32 | python | def test_calculate_fake_user(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].profile.fake_user = True
needs_update[0].profile.save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | def test_calculate_fake_user(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].profile.fake_user = True
needs_update[0].profile.save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]]))<|docstring|>Fake users should not have their caches updated<|endoftext|> |
2618f5dbf1e1436d65c4032a5513222bad748e3f407415a116a115574a33fdaa | def test_calculate_inactive(users_without_with_cache):
'Inactive users should not have their caches updated'
(needs_update, _) = users_without_with_cache
needs_update[0].is_active = False
needs_update[0].save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | Inactive users should not have their caches updated | dashboard/api_test.py | test_calculate_inactive | mitodl/micromasters | 32 | python | def test_calculate_inactive(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].is_active = False
needs_update[0].save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | def test_calculate_inactive(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].is_active = False
needs_update[0].save()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]]))<|docstring|>Inactive users should not have their caches updated<|endoftext|> |
018efa38dde6c203a26bd1fa5c150c333f61dd9f9b07cbfc6b8e7cc3815ce2be | def test_calculate_missing_social_auth(users_without_with_cache):
'Users without a linked social auth should not be counted'
(needs_update, _) = users_without_with_cache
needs_update[0].social_auth.all().delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | Users without a linked social auth should not be counted | dashboard/api_test.py | test_calculate_missing_social_auth | mitodl/micromasters | 32 | python | def test_calculate_missing_social_auth(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].social_auth.all().delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]])) | def test_calculate_missing_social_auth(users_without_with_cache):
(needs_update, _) = users_without_with_cache
needs_update[0].social_auth.all().delete()
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in needs_update[1:]]))<|docstring|>Users without a linked social auth should not be counted<|endoftext|> |
d938524bc5b3125a5c4950aa7e733fc5360b6689612b1db2d275d4d53a4b13f2 | @pytest.mark.parametrize('enrollment,certificate,current_grade,expired', [[None, 0, 0, True], [0, None, 0, True], [0, 0, None, True], [(- 5), 0, 0, False], [0, (- 5), 0, False], [0, 0, (- 5), False], [5, 0, 0, True], [0, 5, 0, True], [0, 0, 5, True]])
def test_calculate_expired(users_without_with_cache, enrollment, certificate, current_grade, expired):
'\n Users with some part of their cache that is expired should show up as needing update\n '
(needs_update, up_to_date) = users_without_with_cache
cache = up_to_date[0].usercacherefreshtime
cache.enrollment = ((now_in_utc() - timedelta(hours=6, minutes=(enrollment - 1))) if (enrollment is not None) else None)
cache.certificate = ((now_in_utc() - timedelta(hours=6, minutes=(certificate - 1))) if (certificate is not None) else None)
cache.current_grade = ((now_in_utc() - timedelta(hours=6, minutes=(current_grade - 1))) if (current_grade is not None) else None)
cache.save()
expected = ((needs_update + [up_to_date[0]]) if expired else needs_update)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected])) | Users with some part of their cache that is expired should show up as needing update | dashboard/api_test.py | test_calculate_expired | mitodl/micromasters | 32 | python | @pytest.mark.parametrize('enrollment,certificate,current_grade,expired', [[None, 0, 0, True], [0, None, 0, True], [0, 0, None, True], [(- 5), 0, 0, False], [0, (- 5), 0, False], [0, 0, (- 5), False], [5, 0, 0, True], [0, 5, 0, True], [0, 0, 5, True]])
def test_calculate_expired(users_without_with_cache, enrollment, certificate, current_grade, expired):
'\n \n '
(needs_update, up_to_date) = users_without_with_cache
cache = up_to_date[0].usercacherefreshtime
cache.enrollment = ((now_in_utc() - timedelta(hours=6, minutes=(enrollment - 1))) if (enrollment is not None) else None)
cache.certificate = ((now_in_utc() - timedelta(hours=6, minutes=(certificate - 1))) if (certificate is not None) else None)
cache.current_grade = ((now_in_utc() - timedelta(hours=6, minutes=(current_grade - 1))) if (current_grade is not None) else None)
cache.save()
expected = ((needs_update + [up_to_date[0]]) if expired else needs_update)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected])) | @pytest.mark.parametrize('enrollment,certificate,current_grade,expired', [[None, 0, 0, True], [0, None, 0, True], [0, 0, None, True], [(- 5), 0, 0, False], [0, (- 5), 0, False], [0, 0, (- 5), False], [5, 0, 0, True], [0, 5, 0, True], [0, 0, 5, True]])
def test_calculate_expired(users_without_with_cache, enrollment, certificate, current_grade, expired):
'\n \n '
(needs_update, up_to_date) = users_without_with_cache
cache = up_to_date[0].usercacherefreshtime
cache.enrollment = ((now_in_utc() - timedelta(hours=6, minutes=(enrollment - 1))) if (enrollment is not None) else None)
cache.certificate = ((now_in_utc() - timedelta(hours=6, minutes=(certificate - 1))) if (certificate is not None) else None)
cache.current_grade = ((now_in_utc() - timedelta(hours=6, minutes=(current_grade - 1))) if (current_grade is not None) else None)
cache.save()
expected = ((needs_update + [up_to_date[0]]) if expired else needs_update)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected]))<|docstring|>Users with some part of their cache that is expired should show up as needing update<|endoftext|> |
b226218dd3a7cc1ce319639583aa3d722d3fb80e111f6ebc1cef256296ddb136 | def test_calculate_exclude_users(users_without_with_cache, patched_redis_keys):
"\n Users in the 'failed update cache' set should be excluded\n "
(needs_update, _) = users_without_with_cache
expected = needs_update[1:]
con = get_redis_connection('redis')
con.sadd(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, needs_update[0].id)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected])) | Users in the 'failed update cache' set should be excluded | dashboard/api_test.py | test_calculate_exclude_users | mitodl/micromasters | 32 | python | def test_calculate_exclude_users(users_without_with_cache, patched_redis_keys):
"\n \n "
(needs_update, _) = users_without_with_cache
expected = needs_update[1:]
con = get_redis_connection('redis')
con.sadd(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, needs_update[0].id)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected])) | def test_calculate_exclude_users(users_without_with_cache, patched_redis_keys):
"\n \n "
(needs_update, _) = users_without_with_cache
expected = needs_update[1:]
con = get_redis_connection('redis')
con.sadd(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, needs_update[0].id)
assert (sorted(api.calculate_users_to_refresh_in_bulk()) == sorted([user.id for user in expected]))<|docstring|>Users in the 'failed update cache' set should be excluded<|endoftext|> |
3892ed836dc26230c0c73f96f0a97ba3f5d0a357de07df926273a8d7d268035a | def test_refresh_user_data(db, mocker):
'refresh_user_data should refresh the cache on all cache types'
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
for cache_type in CachedEdxDataApi.EDX_SUPPORTED_CACHES:
update_cache_mock.assert_any_call(user, edx_api, cache_type, BACKEND_EDX_ORG) | refresh_user_data should refresh the cache on all cache types | dashboard/api_test.py | test_refresh_user_data | mitodl/micromasters | 32 | python | def test_refresh_user_data(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
for cache_type in CachedEdxDataApi.EDX_SUPPORTED_CACHES:
update_cache_mock.assert_any_call(user, edx_api, cache_type, BACKEND_EDX_ORG) | def test_refresh_user_data(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
for cache_type in CachedEdxDataApi.EDX_SUPPORTED_CACHES:
update_cache_mock.assert_any_call(user, edx_api, cache_type, BACKEND_EDX_ORG)<|docstring|>refresh_user_data should refresh the cache on all cache types<|endoftext|> |
72b448f33f9b64fe485f408603b72c540c4013e214019ae9d2ca0fdd724be469 | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_update_cache_for_backend(db, mocker, provider):
'update_cache_for_backend should refresh both courseware backends'
user = _make_fake_real_user()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.update_cache_for_backend(user, provider)
user_social = get_social_auth(user, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider) | update_cache_for_backend should refresh both courseware backends | dashboard/api_test.py | test_update_cache_for_backend | mitodl/micromasters | 32 | python | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_update_cache_for_backend(db, mocker, provider):
user = _make_fake_real_user()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.update_cache_for_backend(user, provider)
user_social = get_social_auth(user, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider) | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_update_cache_for_backend(db, mocker, provider):
user = _make_fake_real_user()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.update_cache_for_backend(user, provider)
user_social = get_social_auth(user, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider)<|docstring|>update_cache_for_backend should refresh both courseware backends<|endoftext|> |
151f1b64028cdc65f19d39e461f8bffc427df1a031d01c3853489db95e826c72 | def test_refresh_missing_user(db, mocker):
"If the user doesn't exist we should skip the refresh"
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(999, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False) | If the user doesn't exist we should skip the refresh | dashboard/api_test.py | test_refresh_missing_user | mitodl/micromasters | 32 | python | def test_refresh_missing_user(db, mocker):
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(999, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False) | def test_refresh_missing_user(db, mocker):
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(999, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False)<|docstring|>If the user doesn't exist we should skip the refresh<|endoftext|> |
df2136bca7891d2a77e98f62918ec5154ead3c93c45f4c4d0a9b39a4cf406c1f | def test_refresh_missing_social_auth(db, mocker):
"If the social auth doesn't exist we should skip the refresh"
user = _make_fake_real_user()
user.social_auth.all().delete()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False) | If the social auth doesn't exist we should skip the refresh | dashboard/api_test.py | test_refresh_missing_social_auth | mitodl/micromasters | 32 | python | def test_refresh_missing_social_auth(db, mocker):
user = _make_fake_real_user()
user.social_auth.all().delete()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False) | def test_refresh_missing_social_auth(db, mocker):
user = _make_fake_real_user()
user.social_auth.all().delete()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
assert (refresh_user_token_mock.called is False)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False)<|docstring|>If the social auth doesn't exist we should skip the refresh<|endoftext|> |
2b2a5f31e1258c9fd70dc61bc8f69ecb889a40b0777a4f4d9ac561fc814a54bd | def test_refresh_failed_oauth_update(db, mocker):
'If the oauth user token refresh fails, we should skip the edx refresh'
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True, side_effect=KeyError)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False)
assert (save_failure_mock.called is True) | If the oauth user token refresh fails, we should skip the edx refresh | dashboard/api_test.py | test_refresh_failed_oauth_update | mitodl/micromasters | 32 | python | def test_refresh_failed_oauth_update(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True, side_effect=KeyError)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False)
assert (save_failure_mock.called is True) | def test_refresh_failed_oauth_update(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True, side_effect=KeyError)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
assert (edx_api_init.called is False)
assert (update_cache_mock.called is False)
assert (save_failure_mock.called is True)<|docstring|>If the oauth user token refresh fails, we should skip the edx refresh<|endoftext|> |
6022d78f3448730c6e0cb64593e4fd71f7c588e25dba53f4d823b7617dc43a21 | def test_refresh_failed_edx_client(db, mocker):
'If we fail to create the edx client, we should skip the edx refresh'
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, side_effect=KeyError)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
assert (update_cache_mock.called is False) | If we fail to create the edx client, we should skip the edx refresh | dashboard/api_test.py | test_refresh_failed_edx_client | mitodl/micromasters | 32 | python | def test_refresh_failed_edx_client(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, side_effect=KeyError)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
assert (update_cache_mock.called is False) | def test_refresh_failed_edx_client(db, mocker):
user = _make_fake_real_user()
user_social = user.social_auth.first()
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, side_effect=KeyError)
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired')
api.refresh_user_data(user.id, BACKEND_EDX_ORG)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, settings.EDXORG_BASE_URL)
assert (update_cache_mock.called is False)<|docstring|>If we fail to create the edx client, we should skip the edx refresh<|endoftext|> |
f179e6350d0d32cc8e7f0e1c9a1a185f74ac0b97bc39268f0fc6c9fe7c69a784 | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_refresh_update_cache(db, mocker, provider):
'If user data cennot be refreshed, save this learner id'
user = _make_fake_real_user()
user_social = user.social_auth.get(provider=provider)
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
failed_cache_type = CachedEdxDataApi.CACHE_TYPES_BACKEND[provider][0]
def _update_cache(user, edx_client, cache_type, provider):
'Fail updating the cache for only the given cache type'
if (cache_type == failed_cache_type):
raise KeyError()
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired', side_effect=_update_cache)
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure', autospec=True)
api.refresh_user_data(user.id, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
assert (save_failure_mock.call_count == 1)
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider) | If user data cennot be refreshed, save this learner id | dashboard/api_test.py | test_refresh_update_cache | mitodl/micromasters | 32 | python | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_refresh_update_cache(db, mocker, provider):
user = _make_fake_real_user()
user_social = user.social_auth.get(provider=provider)
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
failed_cache_type = CachedEdxDataApi.CACHE_TYPES_BACKEND[provider][0]
def _update_cache(user, edx_client, cache_type, provider):
'Fail updating the cache for only the given cache type'
if (cache_type == failed_cache_type):
raise KeyError()
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired', side_effect=_update_cache)
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure', autospec=True)
api.refresh_user_data(user.id, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
assert (save_failure_mock.call_count == 1)
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider) | @pytest.mark.parametrize('provider', COURSEWARE_BACKENDS)
def test_refresh_update_cache(db, mocker, provider):
user = _make_fake_real_user()
user_social = user.social_auth.get(provider=provider)
refresh_user_token_mock = mocker.patch('dashboard.api.utils.refresh_user_token', autospec=True)
edx_api = mocker.Mock()
edx_api_init = mocker.patch('dashboard.api.EdxApi', autospec=True, return_value=edx_api)
failed_cache_type = CachedEdxDataApi.CACHE_TYPES_BACKEND[provider][0]
def _update_cache(user, edx_client, cache_type, provider):
'Fail updating the cache for only the given cache type'
if (cache_type == failed_cache_type):
raise KeyError()
update_cache_mock = mocker.patch('dashboard.api.CachedEdxDataApi.update_cache_if_expired', side_effect=_update_cache)
save_failure_mock = mocker.patch('dashboard.api.save_cache_update_failure', autospec=True)
api.refresh_user_data(user.id, provider)
refresh_user_token_mock.assert_called_once_with(user_social)
edx_api_init.assert_called_once_with(user_social.extra_data, COURSEWARE_BACKEND_URL[provider])
assert (save_failure_mock.call_count == 1)
for cache_type in CachedEdxDataApi.CACHE_TYPES_BACKEND[provider]:
update_cache_mock.assert_any_call(user, edx_api, cache_type, provider)<|docstring|>If user data cennot be refreshed, save this learner id<|endoftext|> |
a089b86f6799e3be6581c4a3b8ce04d014a0f6b5b6d458aefbac8337ef0337bb | def test_save_cache_update_failures(db, patched_redis_keys):
'Count the number of failures and then add to the list to not try to update cache'
user = _make_fake_real_user()
con = get_redis_connection('redis')
user_key = FIELD_USER_ID_BASE_STR.format(user.id)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 1)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 2)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 3)
assert (con.sismember(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, user.id) is True) | Count the number of failures and then add to the list to not try to update cache | dashboard/api_test.py | test_save_cache_update_failures | mitodl/micromasters | 32 | python | def test_save_cache_update_failures(db, patched_redis_keys):
user = _make_fake_real_user()
con = get_redis_connection('redis')
user_key = FIELD_USER_ID_BASE_STR.format(user.id)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 1)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 2)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 3)
assert (con.sismember(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, user.id) is True) | def test_save_cache_update_failures(db, patched_redis_keys):
user = _make_fake_real_user()
con = get_redis_connection('redis')
user_key = FIELD_USER_ID_BASE_STR.format(user.id)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 1)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 2)
save_cache_update_failure(user.id)
assert (int(con.hget(TEST_CACHE_KEY_FAILURES_BY_USER, user_key)) == 3)
assert (con.sismember(TEST_CACHE_KEY_USER_IDS_NOT_TO_UPDATE, user.id) is True)<|docstring|>Count the number of failures and then add to the list to not try to update cache<|endoftext|> |
5488976716f881969d73d4c58fd578a25c127304ca3a29bd10e23ee34eec956a | def test_course_status(self):
'test for CourseStatus'
for attr in ('PASSED', 'NOT_PASSED', 'CURRENTLY_ENROLLED', 'CAN_UPGRADE', 'OFFERED', 'WILL_ATTEND'):
assert hasattr(api.CourseStatus, attr) | test for CourseStatus | dashboard/api_test.py | test_course_status | mitodl/micromasters | 32 | python | def test_course_status(self):
for attr in ('PASSED', 'NOT_PASSED', 'CURRENTLY_ENROLLED', 'CAN_UPGRADE', 'OFFERED', 'WILL_ATTEND'):
assert hasattr(api.CourseStatus, attr) | def test_course_status(self):
for attr in ('PASSED', 'NOT_PASSED', 'CURRENTLY_ENROLLED', 'CAN_UPGRADE', 'OFFERED', 'WILL_ATTEND'):
assert hasattr(api.CourseStatus, attr)<|docstring|>test for CourseStatus<|endoftext|> |
96857e12dcea400ca59ca5617aae6ca0ef0ebfa7f1deb39d7ffe033aa8b74f96 | def test_course_status_all_statuses(self):
'test for CourseStatus.all_statuses'
all_constants = [value for (name, value) in vars(api.CourseStatus).items() if ((not name.startswith('_')) and isinstance(value, str))]
assert (sorted(all_constants) == sorted(api.CourseStatus.all_statuses())) | test for CourseStatus.all_statuses | dashboard/api_test.py | test_course_status_all_statuses | mitodl/micromasters | 32 | python | def test_course_status_all_statuses(self):
all_constants = [value for (name, value) in vars(api.CourseStatus).items() if ((not name.startswith('_')) and isinstance(value, str))]
assert (sorted(all_constants) == sorted(api.CourseStatus.all_statuses())) | def test_course_status_all_statuses(self):
all_constants = [value for (name, value) in vars(api.CourseStatus).items() if ((not name.startswith('_')) and isinstance(value, str))]
assert (sorted(all_constants) == sorted(api.CourseStatus.all_statuses()))<|docstring|>test for CourseStatus.all_statuses<|endoftext|> |
da855cf38acb552247d3f5c9150cf070ff443cb5c08d48d9f3172609ce90ccec | def test_course_run_status(self):
'test for CourseRunStatus'
for attr in ('NOT_ENROLLED', 'CURRENTLY_ENROLLED', 'CHECK_IF_PASSED', 'WILL_ATTEND', 'CAN_UPGRADE', 'NOT_PASSED'):
assert hasattr(api.CourseRunStatus, attr) | test for CourseRunStatus | dashboard/api_test.py | test_course_run_status | mitodl/micromasters | 32 | python | def test_course_run_status(self):
for attr in ('NOT_ENROLLED', 'CURRENTLY_ENROLLED', 'CHECK_IF_PASSED', 'WILL_ATTEND', 'CAN_UPGRADE', 'NOT_PASSED'):
assert hasattr(api.CourseRunStatus, attr) | def test_course_run_status(self):
for attr in ('NOT_ENROLLED', 'CURRENTLY_ENROLLED', 'CHECK_IF_PASSED', 'WILL_ATTEND', 'CAN_UPGRADE', 'NOT_PASSED'):
assert hasattr(api.CourseRunStatus, attr)<|docstring|>test for CourseRunStatus<|endoftext|> |
6cd5bfd25cf6bfe0ba039d1f30738af576b1584a1a3e481a3f860d4729ca3add | def test_course_run_user_status(self):
'test for CourseRunUserStatus'
ustat = api.CourseRunUserStatus(status='status', course_run='run')
assert (ustat.status == 'status')
assert (ustat.course_run == 'run') | test for CourseRunUserStatus | dashboard/api_test.py | test_course_run_user_status | mitodl/micromasters | 32 | python | def test_course_run_user_status(self):
ustat = api.CourseRunUserStatus(status='status', course_run='run')
assert (ustat.status == 'status')
assert (ustat.course_run == 'run') | def test_course_run_user_status(self):
ustat = api.CourseRunUserStatus(status='status', course_run='run')
assert (ustat.status == 'status')
assert (ustat.course_run == 'run')<|docstring|>test for CourseRunUserStatus<|endoftext|> |
7ccd0fb195f50b78c735cd7c5672578c4d80ffa02d35e6fcce35b6d0c1c91c7c | def test_course_run_user_status_repr(self):
'test for CourseRunUserStatus __repr__'
mock_run = MagicMock()
mock_run.title = 'run'
ustat = api.CourseRunUserStatus(status='status', course_run=mock_run)
reps_str_start = '<CourseRunUserStatus for course {course} status {status} at '.format(course=ustat.course_run.title, status=ustat.status)
obj_repr = repr(ustat)
assert obj_repr.startswith(reps_str_start) | test for CourseRunUserStatus __repr__ | dashboard/api_test.py | test_course_run_user_status_repr | mitodl/micromasters | 32 | python | def test_course_run_user_status_repr(self):
mock_run = MagicMock()
mock_run.title = 'run'
ustat = api.CourseRunUserStatus(status='status', course_run=mock_run)
reps_str_start = '<CourseRunUserStatus for course {course} status {status} at '.format(course=ustat.course_run.title, status=ustat.status)
obj_repr = repr(ustat)
assert obj_repr.startswith(reps_str_start) | def test_course_run_user_status_repr(self):
mock_run = MagicMock()
mock_run.title = 'run'
ustat = api.CourseRunUserStatus(status='status', course_run=mock_run)
reps_str_start = '<CourseRunUserStatus for course {course} status {status} at '.format(course=ustat.course_run.title, status=ustat.status)
obj_repr = repr(ustat)
assert obj_repr.startswith(reps_str_start)<|docstring|>test for CourseRunUserStatus __repr__<|endoftext|> |
78cdd6922839ab2a4c99f780cca5d5c469a5e4bc64f2e17da491d3e067e2f135 | def test_course_format_conditional_fields_struct(self):
'\n test for CourseFormatConditionalFields:\n checking the association has the right structure and key/value pairs\n '
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS, dict)
for key in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS:
assert (key in api.CourseStatus.all_statuses())
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key], list)
for assoc in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key]:
assert isinstance(assoc, dict)
assert ('course_run_field' in assoc)
assert ('format_field' in assoc)
assert (assoc['course_run_field'] not in ['', None])
assert (assoc['format_field'] not in ['', None]) | test for CourseFormatConditionalFields:
checking the association has the right structure and key/value pairs | dashboard/api_test.py | test_course_format_conditional_fields_struct | mitodl/micromasters | 32 | python | def test_course_format_conditional_fields_struct(self):
'\n test for CourseFormatConditionalFields:\n checking the association has the right structure and key/value pairs\n '
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS, dict)
for key in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS:
assert (key in api.CourseStatus.all_statuses())
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key], list)
for assoc in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key]:
assert isinstance(assoc, dict)
assert ('course_run_field' in assoc)
assert ('format_field' in assoc)
assert (assoc['course_run_field'] not in [, None])
assert (assoc['format_field'] not in [, None]) | def test_course_format_conditional_fields_struct(self):
'\n test for CourseFormatConditionalFields:\n checking the association has the right structure and key/value pairs\n '
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS, dict)
for key in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS:
assert (key in api.CourseStatus.all_statuses())
assert isinstance(api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key], list)
for assoc in api.CourseFormatConditionalFields.ASSOCIATED_FIELDS[key]:
assert isinstance(assoc, dict)
assert ('course_run_field' in assoc)
assert ('format_field' in assoc)
assert (assoc['course_run_field'] not in [, None])
assert (assoc['format_field'] not in [, None])<|docstring|>test for CourseFormatConditionalFields:
checking the association has the right structure and key/value pairs<|endoftext|> |
7e0327bc7a9d1211c52a27fee068e1e3e89580d29d2a0e5766254012e3a5b2db | def test_course_format_conditional_fields_get(self):
'test for CourseFormatConditionalFields.get_assoc_field'
with self.assertRaises(ImproperlyConfigured):
api.CourseFormatConditionalFields.get_assoc_field('foobar')
assert (len(api.CourseFormatConditionalFields.get_assoc_field(api.CourseStatus.OFFERED)) == 2) | test for CourseFormatConditionalFields.get_assoc_field | dashboard/api_test.py | test_course_format_conditional_fields_get | mitodl/micromasters | 32 | python | def test_course_format_conditional_fields_get(self):
with self.assertRaises(ImproperlyConfigured):
api.CourseFormatConditionalFields.get_assoc_field('foobar')
assert (len(api.CourseFormatConditionalFields.get_assoc_field(api.CourseStatus.OFFERED)) == 2) | def test_course_format_conditional_fields_get(self):
with self.assertRaises(ImproperlyConfigured):
api.CourseFormatConditionalFields.get_assoc_field('foobar')
assert (len(api.CourseFormatConditionalFields.get_assoc_field(api.CourseStatus.OFFERED)) == 2)<|docstring|>test for CourseFormatConditionalFields.get_assoc_field<|endoftext|> |
649b6e05f925a7574bd88836be37f8f4873aa279ccecc1ead0ae578c1cc9ad84 | def create_run(self, course=None, start=None, end=None, enr_start=None, enr_end=None, edx_key=None, title='Title', upgrade_deadline=None):
'helper function to create course runs'
run = CourseRunFactory.create(course=(course or self.course), title=title, start_date=start, end_date=end, enrollment_start=enr_start, enrollment_end=enr_end, upgrade_deadline=upgrade_deadline)
if (edx_key is not None):
run.edx_course_key = edx_key
run.save()
return run | helper function to create course runs | dashboard/api_test.py | create_run | mitodl/micromasters | 32 | python | def create_run(self, course=None, start=None, end=None, enr_start=None, enr_end=None, edx_key=None, title='Title', upgrade_deadline=None):
run = CourseRunFactory.create(course=(course or self.course), title=title, start_date=start, end_date=end, enrollment_start=enr_start, enrollment_end=enr_end, upgrade_deadline=upgrade_deadline)
if (edx_key is not None):
run.edx_course_key = edx_key
run.save()
return run | def create_run(self, course=None, start=None, end=None, enr_start=None, enr_end=None, edx_key=None, title='Title', upgrade_deadline=None):
run = CourseRunFactory.create(course=(course or self.course), title=title, start_date=start, end_date=end, enrollment_start=enr_start, enrollment_end=enr_end, upgrade_deadline=upgrade_deadline)
if (edx_key is not None):
run.edx_course_key = edx_key
run.save()
return run<|docstring|>helper function to create course runs<|endoftext|> |
ade8419a08dda10d61b5a40740e1d4b02fba531cae0e9717d3e43829bbacc386 | def test_format_run_no_run(self):
'Test for format_courserun_for_dashboard if there is no run'
self.assertIsNone(api.format_courserun_for_dashboard(None, api.CourseStatus.PASSED, self.mmtrack)) | Test for format_courserun_for_dashboard if there is no run | dashboard/api_test.py | test_format_run_no_run | mitodl/micromasters | 32 | python | def test_format_run_no_run(self):
self.assertIsNone(api.format_courserun_for_dashboard(None, api.CourseStatus.PASSED, self.mmtrack)) | def test_format_run_no_run(self):
self.assertIsNone(api.format_courserun_for_dashboard(None, api.CourseStatus.PASSED, self.mmtrack))<|docstring|>Test for format_courserun_for_dashboard if there is no run<|endoftext|> |
3099dbc49ab99f08ee2f11c5b4750097502ec2e29238583b772e8f8292b1f22a | def test_format_run_normal(self):
'\n Test for format_courserun_for_dashboard\n '
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard | dashboard/api_test.py | test_format_run_normal | mitodl/micromasters | 32 | python | def test_format_run_normal(self):
'\n \n '
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data) | def test_format_run_normal(self):
'\n \n '
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard<|endoftext|> |
aadfffaf10be10d2c74c10ed2dd2d9d8ea4d7c047b22519122e273e62acdb3fb | def test_format_run_different_position(self):
'\n Test for format_courserun_for_dashboard with different position\n '
self.expected_ret_data['position'] = 56
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack, position=56), self.expected_ret_data) | Test for format_courserun_for_dashboard with different position | dashboard/api_test.py | test_format_run_different_position | mitodl/micromasters | 32 | python | def test_format_run_different_position(self):
'\n \n '
self.expected_ret_data['position'] = 56
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack, position=56), self.expected_ret_data) | def test_format_run_different_position(self):
'\n \n '
self.expected_ret_data['position'] = 56
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack, position=56), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with different position<|endoftext|> |
1d3f36ec5229e3b5fee9ae52bd9430278228d9386b578cfdc0e25039415a49f6 | def test_format_run_with_not_passed(self):
'\n Test for format_courserun_for_dashboard with not passed\n '
self.expected_ret_data.update({'status': api.CourseStatus.NOT_PASSED})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.NOT_PASSED, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard with not passed | dashboard/api_test.py | test_format_run_with_not_passed | mitodl/micromasters | 32 | python | def test_format_run_with_not_passed(self):
'\n \n '
self.expected_ret_data.update({'status': api.CourseStatus.NOT_PASSED})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.NOT_PASSED, self.mmtrack), self.expected_ret_data) | def test_format_run_with_not_passed(self):
'\n \n '
self.expected_ret_data.update({'status': api.CourseStatus.NOT_PASSED})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.NOT_PASSED, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with not passed<|endoftext|> |
fd080edeb2ee0f13ca560cd4bcf1beb56e52eeff1834e706c2894180ff35ea51 | def test_format_run_with_currently_enrolled(self):
'\n Test for format_courserun_for_dashboard with currently enrolled\n '
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33})
del self.expected_ret_data['final_grade']
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard with currently enrolled | dashboard/api_test.py | test_format_run_with_currently_enrolled | mitodl/micromasters | 32 | python | def test_format_run_with_currently_enrolled(self):
'\n \n '
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33})
del self.expected_ret_data['final_grade']
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data) | def test_format_run_with_currently_enrolled(self):
'\n \n '
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33})
del self.expected_ret_data['final_grade']
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with currently enrolled<|endoftext|> |
53411ba681f2152c453eed74f9812580b582f7fc379aec496dffb56964d2c018 | @ddt.data(api.CourseStatus.CURRENTLY_ENROLLED, api.CourseStatus.CAN_UPGRADE)
def test_format_run_currently_enrolled_dont_display_progress(self, status):
'\n test that setting `should_display_progress` to False prevents\n the current grade from being returned\n '
self.expected_ret_data.update({'status': status})
del self.expected_ret_data['final_grade']
if (status == api.CourseStatus.CAN_UPGRADE):
self.expected_ret_data.update({'course_upgrade_deadline': self.crun.upgrade_deadline})
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, status, self.mmtrack), self.expected_ret_data) | test that setting `should_display_progress` to False prevents
the current grade from being returned | dashboard/api_test.py | test_format_run_currently_enrolled_dont_display_progress | mitodl/micromasters | 32 | python | @ddt.data(api.CourseStatus.CURRENTLY_ENROLLED, api.CourseStatus.CAN_UPGRADE)
def test_format_run_currently_enrolled_dont_display_progress(self, status):
'\n test that setting `should_display_progress` to False prevents\n the current grade from being returned\n '
self.expected_ret_data.update({'status': status})
del self.expected_ret_data['final_grade']
if (status == api.CourseStatus.CAN_UPGRADE):
self.expected_ret_data.update({'course_upgrade_deadline': self.crun.upgrade_deadline})
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, status, self.mmtrack), self.expected_ret_data) | @ddt.data(api.CourseStatus.CURRENTLY_ENROLLED, api.CourseStatus.CAN_UPGRADE)
def test_format_run_currently_enrolled_dont_display_progress(self, status):
'\n test that setting `should_display_progress` to False prevents\n the current grade from being returned\n '
self.expected_ret_data.update({'status': status})
del self.expected_ret_data['final_grade']
if (status == api.CourseStatus.CAN_UPGRADE):
self.expected_ret_data.update({'course_upgrade_deadline': self.crun.upgrade_deadline})
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, status, self.mmtrack), self.expected_ret_data)<|docstring|>test that setting `should_display_progress` to False prevents
the current grade from being returned<|endoftext|> |
b26f8cd19bd892c7544cf1d092603ecaeb67d87cb8768b50ec57255dfc3bb7e4 | def test_format_run_dont_display_progress_final_grade(self):
'\n test that we still return a final grade with should_display_progress\n set to False\n '
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data) | test that we still return a final grade with should_display_progress
set to False | dashboard/api_test.py | test_format_run_dont_display_progress_final_grade | mitodl/micromasters | 32 | python | def test_format_run_dont_display_progress_final_grade(self):
'\n test that we still return a final grade with should_display_progress\n set to False\n '
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data) | def test_format_run_dont_display_progress_final_grade(self):
'\n test that we still return a final grade with should_display_progress\n set to False\n '
self.crun.course.should_display_progress = False
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.PASSED, self.mmtrack), self.expected_ret_data)<|docstring|>test that we still return a final grade with should_display_progress
set to False<|endoftext|> |
d22029f9003c928a49aee5fdd71b6724ffdb1be3beb37db6a471272c4455249f | def test_format_run_with_paid_course_run(self):
'\n Test for format_courserun_for_dashboard with a paid course run\n '
self.mmtrack.configure_mock(**{'has_paid.return_value': True})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33, 'has_paid': True})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard with a paid course run | dashboard/api_test.py | test_format_run_with_paid_course_run | mitodl/micromasters | 32 | python | def test_format_run_with_paid_course_run(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_paid.return_value': True})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33, 'has_paid': True})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data) | def test_format_run_with_paid_course_run(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_paid.return_value': True})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CURRENTLY_ENROLLED, 'current_grade': 33.33, 'has_paid': True})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CURRENTLY_ENROLLED, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with a paid course run<|endoftext|> |
4e523ee30fc59e7b0c5dd43fd25bdbecb7b6de60ba6d1c517366a67708ca0a2f | def test_format_run_with_can_upgrade_no_frozen_grade(self):
'\n Test for format_courserun_for_dashboard with can-upgrade status and no frozen grade\n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': False})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'current_grade': 33.33, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard with can-upgrade status and no frozen grade | dashboard/api_test.py | test_format_run_with_can_upgrade_no_frozen_grade | mitodl/micromasters | 32 | python | def test_format_run_with_can_upgrade_no_frozen_grade(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': False})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'current_grade': 33.33, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data) | def test_format_run_with_can_upgrade_no_frozen_grade(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': False})
del self.expected_ret_data['final_grade']
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'current_grade': 33.33, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with can-upgrade status and no frozen grade<|endoftext|> |
df63d4a9358cfd2b596647f548df530f8c5d155df382e65073a8a294a39ff586 | def test_format_run_with_can_upgrade_and_frozen_grade(self):
'\n Test for format_courserun_for_dashboard with can-upgrade status and frozen grade\n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data) | Test for format_courserun_for_dashboard with can-upgrade status and frozen grade | dashboard/api_test.py | test_format_run_with_can_upgrade_and_frozen_grade | mitodl/micromasters | 32 | python | def test_format_run_with_can_upgrade_and_frozen_grade(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data) | def test_format_run_with_can_upgrade_and_frozen_grade(self):
'\n \n '
self.mmtrack.configure_mock(**{'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.CAN_UPGRADE, 'course_upgrade_deadline': self.crun.upgrade_deadline})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.CAN_UPGRADE, self.mmtrack), self.expected_ret_data)<|docstring|>Test for format_courserun_for_dashboard with can-upgrade status and frozen grade<|endoftext|> |
26ed89486f6c665e1eec76114cb462f5c5b717b07f73ed6fd91fcaa4c5f3c3cb | def test_format_run_conditional(self):
'Test for format_courserun_for_dashboard with conditional fields'
self.mmtrack.configure_mock(**{'has_paid.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)))
self.assertEqual(api.format_courserun_for_dashboard(crun, api.CourseStatus.OFFERED, self.mmtrack), {'title': crun.title, 'status': api.CourseStatus.OFFERED, 'id': crun.pk, 'course_id': crun.edx_course_key, 'enrollment_start_date': crun.enrollment_start, 'course_upgrade_deadline': crun.upgrade_deadline, 'fuzzy_enrollment_start_date': crun.fuzzy_enrollment_start_date, 'position': 1, 'course_start_date': crun.start_date, 'course_end_date': crun.end_date, 'courseware_backend': crun.courseware_backend, 'fuzzy_start_date': crun.fuzzy_start_date, 'enrollment_url': crun.enrollment_url, 'has_paid': False, 'year_season': format_season_year_for_course_run(crun)})
with self.assertRaises(ImproperlyConfigured):
api.format_courserun_for_dashboard(crun, 'foo_status', self.mmtrack) | Test for format_courserun_for_dashboard with conditional fields | dashboard/api_test.py | test_format_run_conditional | mitodl/micromasters | 32 | python | def test_format_run_conditional(self):
self.mmtrack.configure_mock(**{'has_paid.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)))
self.assertEqual(api.format_courserun_for_dashboard(crun, api.CourseStatus.OFFERED, self.mmtrack), {'title': crun.title, 'status': api.CourseStatus.OFFERED, 'id': crun.pk, 'course_id': crun.edx_course_key, 'enrollment_start_date': crun.enrollment_start, 'course_upgrade_deadline': crun.upgrade_deadline, 'fuzzy_enrollment_start_date': crun.fuzzy_enrollment_start_date, 'position': 1, 'course_start_date': crun.start_date, 'course_end_date': crun.end_date, 'courseware_backend': crun.courseware_backend, 'fuzzy_start_date': crun.fuzzy_start_date, 'enrollment_url': crun.enrollment_url, 'has_paid': False, 'year_season': format_season_year_for_course_run(crun)})
with self.assertRaises(ImproperlyConfigured):
api.format_courserun_for_dashboard(crun, 'foo_status', self.mmtrack) | def test_format_run_conditional(self):
self.mmtrack.configure_mock(**{'has_paid.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)))
self.assertEqual(api.format_courserun_for_dashboard(crun, api.CourseStatus.OFFERED, self.mmtrack), {'title': crun.title, 'status': api.CourseStatus.OFFERED, 'id': crun.pk, 'course_id': crun.edx_course_key, 'enrollment_start_date': crun.enrollment_start, 'course_upgrade_deadline': crun.upgrade_deadline, 'fuzzy_enrollment_start_date': crun.fuzzy_enrollment_start_date, 'position': 1, 'course_start_date': crun.start_date, 'course_end_date': crun.end_date, 'courseware_backend': crun.courseware_backend, 'fuzzy_start_date': crun.fuzzy_start_date, 'enrollment_url': crun.enrollment_url, 'has_paid': False, 'year_season': format_season_year_for_course_run(crun)})
with self.assertRaises(ImproperlyConfigured):
api.format_courserun_for_dashboard(crun, 'foo_status', self.mmtrack)<|docstring|>Test for format_courserun_for_dashboard with conditional fields<|endoftext|> |
19fd9664f02065e953ec9dd447dbac1d62e431de381369b97567accc23f55abc | def test_has_final_grade_not_enrolled(self):
'\n Test a special case where user has a final grade and he missed the\n deadline and neither he is enrolled in course nor he has paid\n '
self.mmtrack.configure_mock(**{'get_final_grade_percent.return_value': 99.99, 'has_paid.return_value': False, 'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.MISSED_DEADLINE, 'final_grade': 99.99})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.MISSED_DEADLINE, self.mmtrack), self.expected_ret_data) | Test a special case where user has a final grade and he missed the
deadline and neither he is enrolled in course nor he has paid | dashboard/api_test.py | test_has_final_grade_not_enrolled | mitodl/micromasters | 32 | python | def test_has_final_grade_not_enrolled(self):
'\n Test a special case where user has a final grade and he missed the\n deadline and neither he is enrolled in course nor he has paid\n '
self.mmtrack.configure_mock(**{'get_final_grade_percent.return_value': 99.99, 'has_paid.return_value': False, 'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.MISSED_DEADLINE, 'final_grade': 99.99})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.MISSED_DEADLINE, self.mmtrack), self.expected_ret_data) | def test_has_final_grade_not_enrolled(self):
'\n Test a special case where user has a final grade and he missed the\n deadline and neither he is enrolled in course nor he has paid\n '
self.mmtrack.configure_mock(**{'get_final_grade_percent.return_value': 99.99, 'has_paid.return_value': False, 'has_final_grade.return_value': True})
self.expected_ret_data.update({'status': api.CourseStatus.MISSED_DEADLINE, 'final_grade': 99.99})
self.assertEqual(api.format_courserun_for_dashboard(self.crun, api.CourseStatus.MISSED_DEADLINE, self.mmtrack), self.expected_ret_data)<|docstring|>Test a special case where user has a final grade and he missed the
deadline and neither he is enrolled in course nor he has paid<|endoftext|> |
4d5b330a37dafb7735ab4399700430e42470208208b56259121c903cb494c9b8 | def test_status_for_run_not_enrolled(self):
'test for get_status_for_courserun for course without enrollment'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.NOT_ENROLLED)
assert (run_status.course_run == crun) | test for get_status_for_courserun for course without enrollment | dashboard/api_test.py | test_status_for_run_not_enrolled | mitodl/micromasters | 32 | python | def test_status_for_run_not_enrolled(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.NOT_ENROLLED)
assert (run_status.course_run == crun) | def test_status_for_run_not_enrolled(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.NOT_ENROLLED)
assert (run_status.course_run == crun)<|docstring|>test for get_status_for_courserun for course without enrollment<|endoftext|> |
28fd621b8a65695e27c7f100e14fcf8f7b236843c82fc6227f16e04001c8e624 | def test_currently_mmtrack_enrolled(self):
'test for get_status_for_courserun for an enrolled and paid current course'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CURRENTLY_ENROLLED)
assert (run_status.course_run == crun) | test for get_status_for_courserun for an enrolled and paid current course | dashboard/api_test.py | test_currently_mmtrack_enrolled | mitodl/micromasters | 32 | python | def test_currently_mmtrack_enrolled(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CURRENTLY_ENROLLED)
assert (run_status.course_run == crun) | def test_currently_mmtrack_enrolled(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CURRENTLY_ENROLLED)
assert (run_status.course_run == crun)<|docstring|>test for get_status_for_courserun for an enrolled and paid current course<|endoftext|> |
94cebfb23937e400bb0f610dba652d41a0d17201fb1e672c07fbbc48e5facc1e | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@ddt.data((True, False, None, False, 0.1, api.CourseRunStatus.CHECK_IF_PASSED), (False, True, True, True, 1.0, api.CourseRunStatus.CAN_UPGRADE), (False, True, False, False, 0.0, api.CourseRunStatus.MISSED_DEADLINE), (False, True, True, False, 0.0, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_has_final_grade_taken_before_anything_else(self, has_paid_froz, has_frozen, is_upgradable, is_passed, grade, status, mock_is_upgradable):
'\n Tests that if an user has a final grade for the course,\n that is taken in account before checking anything else\n '
mock_is_upgradable.return_value = is_upgradable
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
final_grade = FinalGrade.objects.create(user=self.user, course_run=crun, grade=grade, passed=is_passed, status=FinalGradeStatus.COMPLETE, course_run_paid_on_edx=has_paid_froz)
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'has_paid_final_grade.return_value': has_paid_froz, 'has_final_grade.return_value': has_frozen, 'get_required_final_grade.return_value': final_grade})
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status)
assert (run_status.course_run == crun)
assert (self.mmtrack.is_enrolled.call_count == 0) | Tests that if an user has a final grade for the course,
that is taken in account before checking anything else | dashboard/api_test.py | test_has_final_grade_taken_before_anything_else | mitodl/micromasters | 32 | python | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@ddt.data((True, False, None, False, 0.1, api.CourseRunStatus.CHECK_IF_PASSED), (False, True, True, True, 1.0, api.CourseRunStatus.CAN_UPGRADE), (False, True, False, False, 0.0, api.CourseRunStatus.MISSED_DEADLINE), (False, True, True, False, 0.0, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_has_final_grade_taken_before_anything_else(self, has_paid_froz, has_frozen, is_upgradable, is_passed, grade, status, mock_is_upgradable):
'\n Tests that if an user has a final grade for the course,\n that is taken in account before checking anything else\n '
mock_is_upgradable.return_value = is_upgradable
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
final_grade = FinalGrade.objects.create(user=self.user, course_run=crun, grade=grade, passed=is_passed, status=FinalGradeStatus.COMPLETE, course_run_paid_on_edx=has_paid_froz)
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'has_paid_final_grade.return_value': has_paid_froz, 'has_final_grade.return_value': has_frozen, 'get_required_final_grade.return_value': final_grade})
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status)
assert (run_status.course_run == crun)
assert (self.mmtrack.is_enrolled.call_count == 0) | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@ddt.data((True, False, None, False, 0.1, api.CourseRunStatus.CHECK_IF_PASSED), (False, True, True, True, 1.0, api.CourseRunStatus.CAN_UPGRADE), (False, True, False, False, 0.0, api.CourseRunStatus.MISSED_DEADLINE), (False, True, True, False, 0.0, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_has_final_grade_taken_before_anything_else(self, has_paid_froz, has_frozen, is_upgradable, is_passed, grade, status, mock_is_upgradable):
'\n Tests that if an user has a final grade for the course,\n that is taken in account before checking anything else\n '
mock_is_upgradable.return_value = is_upgradable
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
final_grade = FinalGrade.objects.create(user=self.user, course_run=crun, grade=grade, passed=is_passed, status=FinalGradeStatus.COMPLETE, course_run_paid_on_edx=has_paid_froz)
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'has_paid_final_grade.return_value': has_paid_froz, 'has_final_grade.return_value': has_frozen, 'get_required_final_grade.return_value': final_grade})
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status)
assert (run_status.course_run == crun)
assert (self.mmtrack.is_enrolled.call_count == 0)<|docstring|>Tests that if an user has a final grade for the course,
that is taken in account before checking anything else<|endoftext|> |
8a3de5ae0c07ccdfb0b23a6385c6629e321596cbcdb523923549dddbbe0a2c06 | @ddt.data((True, api.CourseRunStatus.CHECK_IF_PASSED), (False, api.CourseRunStatus.CURRENTLY_ENROLLED))
@ddt.unpack
def test_status_with_frozen_grade(self, has_final_grades, expected_status):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': has_final_grades, 'has_final_grade.return_value': has_final_grades})
if (not has_final_grades):
self.mmtrack.get_final_grade.return_value = None
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
with patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as frozen_mock:
frozen_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun) | test for get_status_for_courserun for a finished course if enrolled
and in case the user has a final grade | dashboard/api_test.py | test_status_with_frozen_grade | mitodl/micromasters | 32 | python | @ddt.data((True, api.CourseRunStatus.CHECK_IF_PASSED), (False, api.CourseRunStatus.CURRENTLY_ENROLLED))
@ddt.unpack
def test_status_with_frozen_grade(self, has_final_grades, expected_status):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': has_final_grades, 'has_final_grade.return_value': has_final_grades})
if (not has_final_grades):
self.mmtrack.get_final_grade.return_value = None
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
with patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as frozen_mock:
frozen_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun) | @ddt.data((True, api.CourseRunStatus.CHECK_IF_PASSED), (False, api.CourseRunStatus.CURRENTLY_ENROLLED))
@ddt.unpack
def test_status_with_frozen_grade(self, has_final_grades, expected_status):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': has_final_grades, 'has_final_grade.return_value': has_final_grades})
if (not has_final_grades):
self.mmtrack.get_final_grade.return_value = None
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
with patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as frozen_mock:
frozen_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun)<|docstring|>test for get_status_for_courserun for a finished course if enrolled
and in case the user has a final grade<|endoftext|> |
47143d675db50df2a37b932de94775422171688c7e4abeca37426693c7b58cbc | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_check_if_passed_if_no_frozen_grade(self, has_frozen_mock, freeze_grades_mock):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has not a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
has_frozen_mock.return_value = True
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CHECK_IF_PASSED)
assert (run_status.course_run == crun)
freeze_grades_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack) | test for get_status_for_courserun for a finished course if enrolled
and in case the user has not a final grade | dashboard/api_test.py | test_check_if_passed_if_no_frozen_grade | mitodl/micromasters | 32 | python | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_check_if_passed_if_no_frozen_grade(self, has_frozen_mock, freeze_grades_mock):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has not a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
has_frozen_mock.return_value = True
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CHECK_IF_PASSED)
assert (run_status.course_run == crun)
freeze_grades_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack) | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_check_if_passed_if_no_frozen_grade(self, has_frozen_mock, freeze_grades_mock):
'\n test for get_status_for_courserun for a finished course if enrolled\n and in case the user has not a final grade\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
has_frozen_mock.return_value = True
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CHECK_IF_PASSED)
assert (run_status.course_run == crun)
freeze_grades_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack)<|docstring|>test for get_status_for_courserun for a finished course if enrolled
and in case the user has not a final grade<|endoftext|> |
cbb3bd63240dd2b6ed4942c2ab48bd0c0582ac45fb5a58a4e2bb7c39ba6b3f17 | def test_read_will_attend(self):
'test for get_status_for_courserun for an enrolled and paid future course'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND)
assert (run_status.course_run == crun)
crun.start_date = None
crun.save()
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND) | test for get_status_for_courserun for an enrolled and paid future course | dashboard/api_test.py | test_read_will_attend | mitodl/micromasters | 32 | python | def test_read_will_attend(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND)
assert (run_status.course_run == crun)
crun.start_date = None
crun.save()
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND) | def test_read_will_attend(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:edX+DemoX+Demo_Course')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND)
assert (run_status.course_run == crun)
crun.start_date = None
crun.save()
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.WILL_ATTEND)<|docstring|>test for get_status_for_courserun for an enrolled and paid future course<|endoftext|> |
10dbc3e2b1c26d8c694122e420f6d1e26292723ab87860662a3c8d89724f4817 | def test_enrolled_not_paid_course(self):
'test for get_status_for_courserun for present and future course with audit enrollment'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
future_run = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:MITx+8.MechCX+2014_T2')
run_status = api.get_status_for_courserun(future_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == future_run)
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == current_run) | test for get_status_for_courserun for present and future course with audit enrollment | dashboard/api_test.py | test_enrolled_not_paid_course | mitodl/micromasters | 32 | python | def test_enrolled_not_paid_course(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
future_run = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:MITx+8.MechCX+2014_T2')
run_status = api.get_status_for_courserun(future_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == future_run)
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == current_run) | def test_enrolled_not_paid_course(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
future_run = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), edx_key='course-v1:MITx+8.MechCX+2014_T2')
run_status = api.get_status_for_courserun(future_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == future_run)
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
assert (run_status.course_run == current_run)<|docstring|>test for get_status_for_courserun for present and future course with audit enrollment<|endoftext|> |
8ac98a7e99c4ef924366180630ba8e6b954e8b538a92c35faccec1260e3d2fbb | def test_enrolled_upgradable(self):
'test for get_status_for_courserun with check if course can be upgraded to paid'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), upgrade_deadline=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now + timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now - timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.MISSED_DEADLINE) | test for get_status_for_courserun with check if course can be upgraded to paid | dashboard/api_test.py | test_enrolled_upgradable | mitodl/micromasters | 32 | python | def test_enrolled_upgradable(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), upgrade_deadline=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now + timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now - timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.MISSED_DEADLINE) | def test_enrolled_upgradable(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
current_run = self.create_run(start=(self.now - timedelta(weeks=1)), end=(self.now + timedelta(weeks=2)), enr_start=(self.now - timedelta(weeks=10)), enr_end=(self.now + timedelta(weeks=1)), upgrade_deadline=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now + timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.CAN_UPGRADE)
current_run.upgrade_deadline = (self.now - timedelta(weeks=1))
current_run.save()
run_status = api.get_status_for_courserun(current_run, self.mmtrack)
assert (run_status.status == api.CourseRunStatus.MISSED_DEADLINE)<|docstring|>test for get_status_for_courserun with check if course can be upgraded to paid<|endoftext|> |
815e6a55fa515f81918d59362b4be14d796bb619587c7635a5afdf200e99f9b2 | def test_no_past_present_future(self):
'\n Test in case the course run returns False to all the\n checks is_current, is_past, is_future, has_final_grades\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=None, end=None, enr_start=None, enr_end=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
crun.fuzzy_start_date = None
crun.save()
with self.assertRaises(ImproperlyConfigured):
api.get_status_for_courserun(crun, self.mmtrack) | Test in case the course run returns False to all the
checks is_current, is_past, is_future, has_final_grades | dashboard/api_test.py | test_no_past_present_future | mitodl/micromasters | 32 | python | def test_no_past_present_future(self):
'\n Test in case the course run returns False to all the\n checks is_current, is_past, is_future, has_final_grades\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=None, end=None, enr_start=None, enr_end=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
crun.fuzzy_start_date = None
crun.save()
with self.assertRaises(ImproperlyConfigured):
api.get_status_for_courserun(crun, self.mmtrack) | def test_no_past_present_future(self):
'\n Test in case the course run returns False to all the\n checks is_current, is_past, is_future, has_final_grades\n '
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': True, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=None, end=None, enr_start=None, enr_end=None, edx_key='course-v1:MITx+8.MechCX+2014_T1')
crun.fuzzy_start_date = None
crun.save()
with self.assertRaises(ImproperlyConfigured):
api.get_status_for_courserun(crun, self.mmtrack)<|docstring|>Test in case the course run returns False to all the
checks is_current, is_past, is_future, has_final_grades<|endoftext|> |
de4fd6d7cacdc310a4da4edb03b32f6e77923bfc2f32743761b0a95da35c9bcf | @ddt.data((False, None, api.CourseRunStatus.MISSED_DEADLINE), (True, False, api.CourseRunStatus.CAN_UPGRADE))
@ddt.unpack
def test_not_paid_in_past(self, is_upgradable, has_final_grades, expected_status):
'test for get_status_for_courserun for course not paid but that is past'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
with patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock) as upgr_mock, patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as froz_mock:
upgr_mock.return_value = is_upgradable
froz_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun) | test for get_status_for_courserun for course not paid but that is past | dashboard/api_test.py | test_not_paid_in_past | mitodl/micromasters | 32 | python | @ddt.data((False, None, api.CourseRunStatus.MISSED_DEADLINE), (True, False, api.CourseRunStatus.CAN_UPGRADE))
@ddt.unpack
def test_not_paid_in_past(self, is_upgradable, has_final_grades, expected_status):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
with patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock) as upgr_mock, patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as froz_mock:
upgr_mock.return_value = is_upgradable
froz_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun) | @ddt.data((False, None, api.CourseRunStatus.MISSED_DEADLINE), (True, False, api.CourseRunStatus.CAN_UPGRADE))
@ddt.unpack
def test_not_paid_in_past(self, is_upgradable, has_final_grades, expected_status):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
with patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock) as upgr_mock, patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock) as froz_mock:
upgr_mock.return_value = is_upgradable
froz_mock.return_value = has_final_grades
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == expected_status)
assert (run_status.course_run == crun)<|docstring|>test for get_status_for_courserun for course not paid but that is past<|endoftext|> |
754782fe8e7e4a10630076d50562c5e08304cdfee48762f86541730729552fb9 | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_not_exists(self, passed, status, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade succeeds\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.return_value = Mock(passed=passed)
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status) | test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, the user does not have a final grade,
and an attempt to freeze the user's final grade succeeds | dashboard/api_test.py | test_not_paid_in_past_grade_frozen_not_exists | mitodl/micromasters | 32 | python | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_not_exists(self, passed, status, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade succeeds\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.return_value = Mock(passed=passed)
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status) | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_not_exists(self, passed, status, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade succeeds\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.return_value = Mock(passed=passed)
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status)<|docstring|>test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, the user does not have a final grade,
and an attempt to freeze the user's final grade succeeds<|endoftext|> |
ea1fc1bfdbee27d62a94de96409d16488d7ca480df7fdc22e8a971211b15d971 | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_not_paid_in_past_grade_frozen_not_exists_raises(self, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade results in an exception\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack) | test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, the user does not have a final grade,
and an attempt to freeze the user's final grade results in an exception | dashboard/api_test.py | test_not_paid_in_past_grade_frozen_not_exists_raises | mitodl/micromasters | 32 | python | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_not_paid_in_past_grade_frozen_not_exists_raises(self, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade results in an exception\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack) | @patch('grades.api.freeze_user_final_grade', autospec=True)
@patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
def test_not_paid_in_past_grade_frozen_not_exists_raises(self, froz_mock, upgr_mock, freeze_mock):
"\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, the user does not have a final grade,\n and an attempt to freeze the user's final grade results in an exception\n "
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.side_effect': FinalGrade.DoesNotExist})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
freeze_mock.side_effect = FreezeGradeFailedException
with self.assertRaises(FreezeGradeFailedException):
api.get_status_for_courserun(crun, self.mmtrack)<|docstring|>test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, the user does not have a final grade,
and an attempt to freeze the user's final grade results in an exception<|endoftext|> |
f40e5744a0af3d038d83142e72b7fe3d7445b202a34e8cbd3d56a650ba1f4b80 | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_exists(self, passed, status, froz_mock, upgr_mock):
'\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, and the user has a final grade.\n '
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.return_value': Mock(passed=passed)})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status) | test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, and the user has a final grade. | dashboard/api_test.py | test_not_paid_in_past_grade_frozen_exists | mitodl/micromasters | 32 | python | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_exists(self, passed, status, froz_mock, upgr_mock):
'\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, and the user has a final grade.\n '
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.return_value': Mock(passed=passed)})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status) | @patch('courses.models.CourseRun.is_upgradable', new_callable=PropertyMock)
@patch('courses.models.CourseRun.has_frozen_grades', new_callable=PropertyMock)
@ddt.data((True, api.CourseRunStatus.CAN_UPGRADE), (False, api.CourseRunStatus.NOT_PASSED))
@ddt.unpack
def test_not_paid_in_past_grade_frozen_exists(self, passed, status, froz_mock, upgr_mock):
'\n test for get_status_for_courserun for a past course run that is\n not paid, grades are already frozen, and the user has a final grade.\n '
upgr_mock.return_value = True
froz_mock.return_value = True
self.mmtrack.configure_mock(**{'is_enrolled.return_value': True, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': False, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False, 'get_required_final_grade.return_value': Mock(passed=passed)})
crun = self.create_run(start=(self.now - timedelta(weeks=52)), end=(self.now - timedelta(weeks=45)), enr_start=(self.now - timedelta(weeks=62)), enr_end=(self.now - timedelta(weeks=53)), edx_key='course-v1:MITx+8.MechCX+2014_T1')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert (run_status.status == status)<|docstring|>test for get_status_for_courserun for a past course run that is
not paid, grades are already frozen, and the user has a final grade.<|endoftext|> |
a8a66f061266e0c3c73b2d87bfad1630e5fa790e1994005ef86e810640e3c09e | def test_status_for_run_not_enrolled_but_paid(self):
'test for get_status_for_courserun for course without enrollment and it is paid'
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.PAID_BUT_NOT_ENROLLED)
assert (run_status.course_run == crun) | test for get_status_for_courserun for course without enrollment and it is paid | dashboard/api_test.py | test_status_for_run_not_enrolled_but_paid | mitodl/micromasters | 32 | python | def test_status_for_run_not_enrolled_but_paid(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.PAID_BUT_NOT_ENROLLED)
assert (run_status.course_run == crun) | def test_status_for_run_not_enrolled_but_paid(self):
self.mmtrack.configure_mock(**{'is_enrolled.return_value': False, 'is_enrolled_mmtrack.return_value': False, 'has_paid.return_value': True, 'has_paid_final_grade.return_value': False, 'has_final_grade.return_value': False})
crun = self.create_run(start=(self.now + timedelta(weeks=52)), end=(self.now + timedelta(weeks=62)), enr_start=(self.now + timedelta(weeks=40)), enr_end=(self.now + timedelta(weeks=50)), edx_key='foo_edx_key')
run_status = api.get_status_for_courserun(crun, self.mmtrack)
assert isinstance(run_status, api.CourseRunUserStatus)
assert (run_status.status == api.CourseRunStatus.PAID_BUT_NOT_ENROLLED)
assert (run_status.course_run == crun)<|docstring|>test for get_status_for_courserun for course without enrollment and it is paid<|endoftext|> |
f003c1bc08b214cab147daf58c351106c3b1922f2978d95bbc9a4b577f82ecb5 | def assert_course_equal(self, course, course_data_from_call, can_schedule_exam=False, exam_register_end_date='', exam_url='', exams_schedulable_in_future=None, exam_date_next_semester='', current_exam_dates='', has_to_pay=False, has_exam=False, is_elective=False, proct_exams=None):
'Helper to format the course info'
proct_exams = (proct_exams or [])
exams_schedulable_in_future = (exams_schedulable_in_future or [])
expected_data = {'id': course.pk, 'title': course.title, 'position_in_program': course.position_in_program, 'description': course.description, 'prerequisites': course.prerequisites, 'has_contact_email': bool(course.contact_email), 'can_schedule_exam': can_schedule_exam, 'exam_register_end_date': exam_register_end_date, 'exam_url': exam_url, 'exams_schedulable_in_future': exams_schedulable_in_future, 'exam_date_next_semester': exam_date_next_semester, 'current_exam_dates': current_exam_dates, 'has_to_pay': has_to_pay, 'proctorate_exams_grades': proct_exams, 'is_elective': is_elective, 'has_exam': has_exam, 'certificate_url': '', 'overall_grade': ''}
del course_data_from_call['runs']
self.assertEqual(expected_data, course_data_from_call) | Helper to format the course info | dashboard/api_test.py | assert_course_equal | mitodl/micromasters | 32 | python | def assert_course_equal(self, course, course_data_from_call, can_schedule_exam=False, exam_register_end_date=, exam_url=, exams_schedulable_in_future=None, exam_date_next_semester=, current_exam_dates=, has_to_pay=False, has_exam=False, is_elective=False, proct_exams=None):
proct_exams = (proct_exams or [])
exams_schedulable_in_future = (exams_schedulable_in_future or [])
expected_data = {'id': course.pk, 'title': course.title, 'position_in_program': course.position_in_program, 'description': course.description, 'prerequisites': course.prerequisites, 'has_contact_email': bool(course.contact_email), 'can_schedule_exam': can_schedule_exam, 'exam_register_end_date': exam_register_end_date, 'exam_url': exam_url, 'exams_schedulable_in_future': exams_schedulable_in_future, 'exam_date_next_semester': exam_date_next_semester, 'current_exam_dates': current_exam_dates, 'has_to_pay': has_to_pay, 'proctorate_exams_grades': proct_exams, 'is_elective': is_elective, 'has_exam': has_exam, 'certificate_url': , 'overall_grade': }
del course_data_from_call['runs']
self.assertEqual(expected_data, course_data_from_call) | def assert_course_equal(self, course, course_data_from_call, can_schedule_exam=False, exam_register_end_date=, exam_url=, exams_schedulable_in_future=None, exam_date_next_semester=, current_exam_dates=, has_to_pay=False, has_exam=False, is_elective=False, proct_exams=None):
proct_exams = (proct_exams or [])
exams_schedulable_in_future = (exams_schedulable_in_future or [])
expected_data = {'id': course.pk, 'title': course.title, 'position_in_program': course.position_in_program, 'description': course.description, 'prerequisites': course.prerequisites, 'has_contact_email': bool(course.contact_email), 'can_schedule_exam': can_schedule_exam, 'exam_register_end_date': exam_register_end_date, 'exam_url': exam_url, 'exams_schedulable_in_future': exams_schedulable_in_future, 'exam_date_next_semester': exam_date_next_semester, 'current_exam_dates': current_exam_dates, 'has_to_pay': has_to_pay, 'proctorate_exams_grades': proct_exams, 'is_elective': is_elective, 'has_exam': has_exam, 'certificate_url': , 'overall_grade': }
del course_data_from_call['runs']
self.assertEqual(expected_data, course_data_from_call)<|docstring|>Helper to format the course info<|endoftext|> |
865380883a2ba8a74152f3ff14a92030973e81639a324eab76ac2c8dd5e4c8d3 | def get_mock_run_status_func(self, status, specific_run, other_run_status):
'Helper method to return mocked functions for getting course run status'
def mock_return_status(actual_course_run, *args, **kargs):
'Mock function for get_status_for_courserun'
if (actual_course_run == specific_run):
return api.CourseRunUserStatus(status=status, course_run=actual_course_run)
return api.CourseRunUserStatus(status=other_run_status, course_run=actual_course_run)
return mock_return_status | Helper method to return mocked functions for getting course run status | dashboard/api_test.py | get_mock_run_status_func | mitodl/micromasters | 32 | python | def get_mock_run_status_func(self, status, specific_run, other_run_status):
def mock_return_status(actual_course_run, *args, **kargs):
'Mock function for get_status_for_courserun'
if (actual_course_run == specific_run):
return api.CourseRunUserStatus(status=status, course_run=actual_course_run)
return api.CourseRunUserStatus(status=other_run_status, course_run=actual_course_run)
return mock_return_status | def get_mock_run_status_func(self, status, specific_run, other_run_status):
def mock_return_status(actual_course_run, *args, **kargs):
'Mock function for get_status_for_courserun'
if (actual_course_run == specific_run):
return api.CourseRunUserStatus(status=status, course_run=actual_course_run)
return api.CourseRunUserStatus(status=other_run_status, course_run=actual_course_run)
return mock_return_status<|docstring|>Helper method to return mocked functions for getting course run status<|endoftext|> |
96ed81c2cfeb943ea1ee0993adb4180bc218b4fab3d74df61547e6ea264efaf0 | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_no_runs(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test for get_info_for_course for course with no runs'
self.assert_course_equal(self.course_noruns, api.get_info_for_course(self.course_noruns, self.mmtrack))
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test for get_info_for_course for course with no runs | dashboard/api_test.py | test_info_no_runs | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_no_runs(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.assert_course_equal(self.course_noruns, api.get_info_for_course(self.course_noruns, self.mmtrack))
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_no_runs(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.assert_course_equal(self.course_noruns, api.get_info_for_course(self.course_noruns, self.mmtrack))
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test for get_info_for_course for course with no runs<|endoftext|> |
0760c3efba8611a5bdfaebbc44a628edf7b35050cae0195eef46f52ce93e4689 | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_with_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test that get_info_for_course indicates that a course has a contact_email '
course = CourseFactory.create(contact_email='[email protected]')
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is True)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test that get_info_for_course indicates that a course has a contact_email | dashboard/api_test.py | test_info_with_contact_email | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_with_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
' '
course = CourseFactory.create(contact_email='[email protected]')
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is True)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_with_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
' '
course = CourseFactory.create(contact_email='[email protected]')
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is True)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test that get_info_for_course indicates that a course has a contact_email<|endoftext|> |
78f06ed081ca4cca4c3c0b9abc0a74b75c3afc820fe8be5a6cc9de335d9fbe46 | @patch('dashboard.api.is_exam_schedulable')
@ddt.data(True, False)
def test_info_returns_exam_schedulable(self, boolean, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test that get_info_for_course returns whether the exam is schedulable'
course = CourseFactory.create(contact_email=None)
mock_schedulable.return_value = boolean
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['can_schedule_exam'] == boolean)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test that get_info_for_course returns whether the exam is schedulable | dashboard/api_test.py | test_info_returns_exam_schedulable | mitodl/micromasters | 32 | python | @patch('dashboard.api.is_exam_schedulable')
@ddt.data(True, False)
def test_info_returns_exam_schedulable(self, boolean, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
course = CourseFactory.create(contact_email=None)
mock_schedulable.return_value = boolean
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['can_schedule_exam'] == boolean)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.is_exam_schedulable')
@ddt.data(True, False)
def test_info_returns_exam_schedulable(self, boolean, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
course = CourseFactory.create(contact_email=None)
mock_schedulable.return_value = boolean
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['can_schedule_exam'] == boolean)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test that get_info_for_course returns whether the exam is schedulable<|endoftext|> |
affbc8f6a9f0162ec7a832303b1c159f86165a7f809aa76b7b6cabd17366e281 | @patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_returns_has_exam(self, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test that get_info_for_course returns whether the course has an exam module or not'
course = CourseFactory.create(contact_email=None)
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack))
exam_run = ExamRunFactory.create(course=course)
exam_register_end_date = '{}'.format(exam_run.date_last_schedulable.strftime('%B %-d, %I:%M %p %Z'))
current_exam_dates = '{} and {}'.format(exam_run.date_first_eligible.strftime('%b %-d'), exam_run.date_last_eligible.strftime('%b %-d, %Y'))
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack), has_exam=True, exam_register_end_date=exam_register_end_date, current_exam_dates=current_exam_dates)
assert (mock_schedulable.call_count == 2)
assert (mock_has_to_pay.call_count == 2)
assert (mock_future_exams.call_count == 2)
assert (mock_get_cert.call_count == 2)
assert (mock_exam_url.call_count == 2) | test that get_info_for_course returns whether the course has an exam module or not | dashboard/api_test.py | test_info_returns_has_exam | mitodl/micromasters | 32 | python | @patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_returns_has_exam(self, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
course = CourseFactory.create(contact_email=None)
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack))
exam_run = ExamRunFactory.create(course=course)
exam_register_end_date = '{}'.format(exam_run.date_last_schedulable.strftime('%B %-d, %I:%M %p %Z'))
current_exam_dates = '{} and {}'.format(exam_run.date_first_eligible.strftime('%b %-d'), exam_run.date_last_eligible.strftime('%b %-d, %Y'))
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack), has_exam=True, exam_register_end_date=exam_register_end_date, current_exam_dates=current_exam_dates)
assert (mock_schedulable.call_count == 2)
assert (mock_has_to_pay.call_count == 2)
assert (mock_future_exams.call_count == 2)
assert (mock_get_cert.call_count == 2)
assert (mock_exam_url.call_count == 2) | @patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_returns_has_exam(self, mock_schedulable, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
course = CourseFactory.create(contact_email=None)
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack))
exam_run = ExamRunFactory.create(course=course)
exam_register_end_date = '{}'.format(exam_run.date_last_schedulable.strftime('%B %-d, %I:%M %p %Z'))
current_exam_dates = '{} and {}'.format(exam_run.date_first_eligible.strftime('%b %-d'), exam_run.date_last_eligible.strftime('%b %-d, %Y'))
self.assert_course_equal(course, api.get_info_for_course(course, self.mmtrack), has_exam=True, exam_register_end_date=exam_register_end_date, current_exam_dates=current_exam_dates)
assert (mock_schedulable.call_count == 2)
assert (mock_has_to_pay.call_count == 2)
assert (mock_future_exams.call_count == 2)
assert (mock_get_cert.call_count == 2)
assert (mock_exam_url.call_count == 2)<|docstring|>test that get_info_for_course returns whether the course has an exam module or not<|endoftext|> |
691acbc4e7e5f8b6092aef0bd6e79bfa7f52d4c080fbcc7cfcc8dec65fd29d41 | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_without_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test that get_info_for_course indicates that a course has no contact_email '
course = CourseFactory.create(contact_email=None)
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is False)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test that get_info_for_course indicates that a course has no contact_email | dashboard/api_test.py | test_info_without_contact_email | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_without_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
' '
course = CourseFactory.create(contact_email=None)
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is False)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_without_contact_email(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
' '
course = CourseFactory.create(contact_email=None)
course_info = api.get_info_for_course(course, self.mmtrack)
assert (course_info['has_contact_email'] is False)
assert (mock_format.called is False)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test that get_info_for_course indicates that a course has no contact_email<|endoftext|> |
c272fb1690e965225d4139e6e7b817943d13d4d67563be7ad8c69a1ba724322e | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test for get_info_for_course for course with with an offered run'
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test for get_info_for_course for course with with an offered run | dashboard/api_test.py | test_info_not_enrolled_offered | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test for get_info_for_course for course with with an offered run<|endoftext|> |
790c7ee1188ca34e9fd9528ce6df7b8e9dc16e274ab90402acafbb117677bd46 | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_but_paid(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test for get_info_for_course for course with with a paid but not enrolled run'
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.PAID_BUT_NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.PAID_BUT_NOT_ENROLLED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test for get_info_for_course for course with with a paid but not enrolled run | dashboard/api_test.py | test_info_not_enrolled_but_paid | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_but_paid(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.PAID_BUT_NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.PAID_BUT_NOT_ENROLLED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_enrolled_but_paid(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, return_value=api.CourseRunUserStatus(status=api.CourseRunStatus.PAID_BUT_NOT_ENROLLED, course_run=self.course_run)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_called_once_with(self.course_run, api.CourseStatus.PAID_BUT_NOT_ENROLLED, self.mmtrack, position=1)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test for get_info_for_course for course with with a paid but not enrolled run<|endoftext|> |
b00b43df8a939eee9ba5f553522ac0a6dd6894eb26de1eb9e8be09692be4c6c9 | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_passed_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
'test for get_info_for_course for course with a run not passed and another offered'
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, side_effect=self.get_mock_run_status_func(api.CourseRunStatus.NOT_PASSED, self.course_run_ver, api.CourseRunStatus.NOT_ENROLLED)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_any_call(self.course_run_ver, api.CourseStatus.NOT_PASSED, self.mmtrack, position=1)
mock_format.assert_any_call(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=2)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | test for get_info_for_course for course with a run not passed and another offered | dashboard/api_test.py | test_info_not_passed_offered | mitodl/micromasters | 32 | python | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_passed_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, side_effect=self.get_mock_run_status_func(api.CourseRunStatus.NOT_PASSED, self.course_run_ver, api.CourseRunStatus.NOT_ENROLLED)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_any_call(self.course_run_ver, api.CourseStatus.NOT_PASSED, self.mmtrack, position=1)
mock_format.assert_any_call(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=2)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1) | @patch('dashboard.api.format_courserun_for_dashboard', autospec=True)
@patch('dashboard.api.is_exam_schedulable', return_value=False)
def test_info_not_passed_offered(self, mock_schedulable, mock_format, mock_get_cert, mock_future_exams, mock_has_to_pay, mock_exam_url):
self.mmtrack.configure_mock(**{'is_enrolled_mmtrack.return_value': True})
with patch('dashboard.api.get_status_for_courserun', autospec=True, side_effect=self.get_mock_run_status_func(api.CourseRunStatus.NOT_PASSED, self.course_run_ver, api.CourseRunStatus.NOT_ENROLLED)):
self.assert_course_equal(self.course, api.get_info_for_course(self.course, self.mmtrack))
mock_format.assert_any_call(self.course_run_ver, api.CourseStatus.NOT_PASSED, self.mmtrack, position=1)
mock_format.assert_any_call(self.course_run, api.CourseStatus.OFFERED, self.mmtrack, position=2)
assert (mock_schedulable.call_count == 1)
assert (mock_has_to_pay.call_count == 1)
assert (mock_future_exams.call_count == 1)
assert (mock_get_cert.call_count == 1)
assert (mock_exam_url.call_count == 1)<|docstring|>test for get_info_for_course for course with a run not passed and another offered<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.