Best Python code snippet using autotest_python
lammps.py
Source:lammps.py
...44 None45 """46 pickle.dump({"c": command, "d": data}, self._process.stdin)47 self._process.stdin.flush()48 def _receive(self):49 """50 Receive data from the Lammps library51 Parameters52 ----------53 None54 Returns55 -------56 data : string57 data from the command58 """59 output = pickle.load(self._process.stdout)60 return output61 @property62 def version(self):63 """64 Get the version of lammps65 Parameters66 ----------67 None68 Returns69 -------70 version: string71 version string of lammps72 """73 self._send(command="get_version", data=[])74 return self._receive()75 def file(self, inputfile):76 """77 Read script from an input file78 Parameters79 ----------80 inputfile: string81 name of inputfile82 Returns83 -------84 None85 """86 if not os.path.exists(inputfile):87 raise FileNotFoundError("Input file does not exist")88 self._send(command="get_file", data=[inputfile])89 _ = self._receive()90 # TODO91 def extract_setting(self, *args):92 self._send(command="extract_setting", data=list(args))93 return self._receive()94 def extract_global(self, name):95 """96 Extract value of global simulation parameters97 Parameters98 ----------99 name : string100 see notes for a set of possible options101 Notes102 -----103 The possible options for `name` are-104 "dt", "boxlo", "boxhi", "boxxlo", "boxxhi",105 "boxylo", "boxyhi", "boxzlo", "boxzhi", "periodicity",106 "xy", "xz", "yz", "natoms", "nbonds", "nangles",107 "ndihedrals", "nimpropers", "nlocal", "nghost",108 "nmax", "ntypes", "ntimestep", "units", "triclinic",109 "q_flag", "atime", "atimestep"110 Also global constants defined by units can be accessed-111 "boltz", "hplanck", "mvv2e", "ftm2v", "mv2d",112 "nktv2p", "qqr2e", "qe2f", "vxmu2f", "xxt2kmu",113 "dielectric", "qqr2e", "e_mass", "hhmrr2e",114 "mvh2r", "angstrom", "femtosecond", "qelectron"115 """116 self._send(command="extract_global", data=[name])117 return self._receive()118 def extract_box(self):119 """120 Get the simulation box121 Parameters122 ----------123 None124 Returns125 -------126 box : list127 of the form `[boxlo,boxhi,xy,yz,xz,periodicity,box_change]` where128 `boxlo` and `boxhi` are lower and upper bounds of the box in three dimensions,129 `xy, yz, xz` are the box tilts, `periodicity` is an array which shows if130 the box is periodic in three dimensions.131 """132 self._send(command="extract_box", data=[])133 return self._receive()134 def extract_atom(self, name):135 """136 Extract a property of the atoms137 Parameters138 ----------139 name : {'x', 'mass', 'id', 'type', 'mask', 'v', 'f',140 'molecule', 'q', 'mu', 'omega', 'angmom', 'torque', 'radius'}141 the property of atom to be extracted142 Returns143 -------144 val : array of length n_atoms145 If the requested name has multiple dimensions, output146 will be a multi-dimensional array.147 Notes148 -----149 This method only gathers information from the current processor.150 Rest of the values would be zero.151 See Also152 --------153 scatter_atoms154 """155 self._send(command="extract_atom", data=list([name]))156 return self._receive()157 def extract_fix(self, *args):158 """159 Extract a fix value160 Parameters161 ----------162 id: string163 id of the fix164 style: {0, 1, 2}165 0 - global data166 1 - per-atom data167 2 - local data168 type: {0, 1, 2}169 0 - scalar170 1 - vector171 2 - array172 i: int, optional173 index to select fix output174 j: int, optional175 index to select fix output176 Returns177 -------178 value179 Fix data corresponding to the requested dimensions180 """181 self._send(command="extract_fix", data=list(args))182 return self._receive()183 def extract_variable(self, *args):184 """185 Extract the value of a variable186 Parameters187 ----------188 name: string189 name of the variable190 group: string191 group id (ignored for equal style variables)192 flag: {0, 1}193 0 - equal style variable194 1 - atom style variable195 Returns196 -------197 data198 value of variable depending on the requested dimension199 Notes200 -----201 Currently only returns the information provided on a single processor202 """203 self._send(command="extract_variable", data=list(args))204 return self._receive()205 @property206 def natoms(self):207 return self.get_natoms()208 def get_natoms(self):209 """210 Get the number of atoms211 Parameters212 ----------213 None214 Returns215 -------216 natoms : int217 number of atoms218 """219 self._send(command="get_natoms", data=[])220 return self._receive()221 def set_variable(self, *args):222 """223 Set the value of a string style variable224 Parameters225 ----------226 name: string227 name of the variable228 value: string229 value of the variable230 Returns231 -------232 flag : int233 0 if successfull, -1 otherwise234 """235 self._send(command="set_variable", data=list(args))236 return self._receive()237 def reset_box(self, *args):238 """239 Reset the simulation box240 Parameters241 ----------242 boxlo: array of floats243 lower bound of box in three dimensions244 boxhi: array of floats245 upper bound of box in three dimensions246 xy, yz, xz : floats247 box tilts248 """249 self._send(command="reset_box", data=list(args))250 _ = self._receive()251 def generate_atoms(252 self, ids=None, type=None, x=None, v=None, image=None, shrinkexceed=False253 ):254 """255 Create atoms on all procs256 Parameters257 ----------258 ids : list of ints, optional259 ids of N atoms that need to be created260 if not specified, ids from 1 to N are assigned261 type : list of atom types, optional262 type of N atoms, if not specied, all atoms are assigned as type 1263 x: list of positions264 list of the type `[posx, posy, posz]` for N atoms265 v: list of velocities266 list of the type `[vx, vy, vz]` for N atoms267 image: list of ints, optional268 if not specified a list of 0s will be used.269 shrinkexceed: bool, optional270 default False271 Returns272 -------273 None274 """275 self.create_atoms(276 ids=ids, type=type, x=x, v=v, image=image, shrinkexceed=shrinkexceed277 )278 def create_atoms(279 self, ids=None, type=None, x=None, v=None, image=None, shrinkexceed=False280 ):281 """282 Create atoms on all procs283 Parameters284 ----------285 ids : list of ints, optional286 ids of N atoms that need to be created287 if not specified, ids from 1 to N are assigned288 type : list of atom types, optional289 type of N atoms, if not specied, all atoms are assigned as type 1290 x: list of positions291 list of the type `[posx, posy, posz]` for N atoms292 v: list of velocities293 list of the type `[vx, vy, vz]` for N atoms294 image: list of ints, optional295 if not specified a list of 0s will be used.296 shrinkexceed: bool, optional297 default False298 Returns299 -------300 None301 """302 if x is not None:303 natoms = len(x)304 if type is None:305 type = [1] * natoms306 if ids is None:307 ids = list(range(1, natoms + 1))308 if image is None:309 image = [0] * natoms310 funct_args = [natoms, ids, type, x, v, image, shrinkexceed]311 self._send(command="create_atoms", data=funct_args)312 _ = self._receive()313 else:314 raise TypeError("Value of x cannot be None")315 @property316 def has_exceptions(self):317 """Return whether the LAMMPS shared library was compiled with C++ exceptions handling enabled"""318 self._send(command="has_exceptions", data=[])319 return self._receive()320 @property321 def has_gzip_support(self):322 self._send(command="has_gzip_support", data=[])323 return self._receive()324 @property325 def has_png_support(self):326 self._send(command="has_png_support", data=[])327 return self._receive()328 @property329 def has_jpeg_support(self):330 self._send(command="has_jpeg_support", data=[])331 return self._receive()332 @property333 def has_ffmpeg_support(self):334 self._send(command="has_ffmpeg_support", data=[])335 return self._receive()336 @property337 def installed_packages(self):338 self._send(command="get_installed_packages", data=[])339 return self._receive()340 def set_fix_external_callback(self, *args):341 self._send(command="set_fix_external_callback", data=list(args))342 def get_neighlist(self, *args):343 """Returns an instance of :class:`NeighList` which wraps access to the neighbor list with the given index344 :param idx: index of neighbor list345 :type idx: int346 :return: an instance of :class:`NeighList` wrapping access to neighbor list data347 :rtype: NeighList348 """349 self._send(command="get_neighlist", data=list(args))350 return self._receive()351 def find_pair_neighlist(self, *args):352 """Find neighbor list index of pair style neighbor list353 Try finding pair instance that matches style. If exact is set, the pair must354 match style exactly. If exact is 0, style must only be contained. If pair is355 of style pair/hybrid, style is instead matched the nsub-th hybrid sub-style.356 Once the pair instance has been identified, multiple neighbor list requests357 may be found. Every neighbor list is uniquely identified by its request358 index. Thus, providing this request index ensures that the correct neighbor359 list index is returned.360 :param style: name of pair style that should be searched for361 :type style: string362 :param exact: controls whether style should match exactly or only must be contained in pair style name, defaults to True363 :type exact: bool, optional364 :param nsub: match nsub-th hybrid sub-style, defaults to 0365 :type nsub: int, optional366 :param request: index of neighbor list request, in case there are more than one, defaults to 0367 :type request: int, optional368 :return: neighbor list index if found, otherwise -1369 :rtype: int370 """371 self._send(command="find_pair_neighlist", data=list(args))372 return self._receive()373 def find_fix_neighlist(self, *args):374 """Find neighbor list index of fix neighbor list375 :param fixid: name of fix376 :type fixid: string377 :param request: index of neighbor list request, in case there are more than one, defaults to 0378 :type request: int, optional379 :return: neighbor list index if found, otherwise -1380 :rtype: int381 """382 self._send(command="find_fix_neighlist", data=list(args))383 return self._receive()384 def find_compute_neighlist(self, *args):385 """Find neighbor list index of compute neighbor list386 :param computeid: name of compute387 :type computeid: string388 :param request: index of neighbor list request, in case there are more than one, defaults to 0389 :type request: int, optional390 :return: neighbor list index if found, otherwise -1391 :rtype: int392 """393 self._send(command="find_compute_neighlist", data=list(args))394 return self._receive()395 def get_neighlist_size(self, *args):396 """Return the number of elements in neighbor list with the given index397 :param idx: neighbor list index398 :type idx: int399 :return: number of elements in neighbor list with index idx400 :rtype: int401 """402 self._send(command="get_neighlist_size", data=list(args))403 return self._receive()404 def get_neighlist_element_neighbors(self, *args):405 self._send(command="get_neighlist_element_neighbors", data=list(args))406 return self._receive()407 def command(self, cmd):408 """409 Send a command to the lammps object410 Parameters411 ----------412 cmd : string, list of strings413 command to be sent414 Returns415 -------416 None417 """418 if isinstance(cmd, list):419 for c in cmd:420 self._send(command="command", data=c)421 _ = self._receive()422 elif len(cmd.split("\n")) > 1:423 for c in cmd.split("\n"):424 self._send(command="command", data=c)425 _ = self._receive()426 else:427 self._send(command="command", data=cmd)428 _ = self._receive()429 def gather_atoms(self, *args, concat=False, ids=None):430 """431 Gather atom properties432 Parameters433 ----------434 name : {'x', 'mass', 'id', 'type', 'mask', 'v', 'f',435 'molecule', 'q', 'mu', 'omega', 'angmom', 'torque', 'radius'}436 the property of atom to be extracted437 concat : bool, optional. Default False438 If True, gather information from all processors,439 but not sorted according to Atom ids440 ids : list, optional. Default None441 If a list of ids are provided, the required information442 for only those atoms are returned443 Returns444 -------445 val : array of length n_atoms sorted by atom ids446 If the requested name has multiple dimensions, output447 will be a multi-dimensional array.448 Notes449 -----450 This method gathers information from all processors.451 See Also452 --------453 extract_atoms454 """455 if concat:456 self._send(command="gather_atoms_concat", data=list(args))457 elif ids is not None:458 lenids = len(ids)459 args = list(args)460 args.append(len(ids))461 args.append(ids)462 self._send(command="gather_atoms_subset", data=args)463 else:464 self._send(command="gather_atoms", data=list(args))465 return self._receive()466 def scatter_atoms(self, *args, ids=None):467 """468 Scatter atoms for the lammps library469 Args:470 *args:471 """472 if ids is not None:473 lenids = len(ids)474 args = list(args)475 args.append(len(ids))476 args.append(ids)477 self._send(command="scatter_atoms_subset", data=args)478 _ = self._receive()479 else:480 self._send(command="scatter_atoms", data=list(args))481 _ = self._receive()482 def get_thermo(self, *args):483 """484 Return current value of thermo keyword485 Parameters486 ----------487 name : string488 name of the thermo keyword489 Returns490 -------491 val492 value of the thermo keyword493 """494 self._send(command="get_thermo", data=list(args))495 return self._receive()496 # TODO497 def extract_compute(self, id, style, type, length=0, width=0):498 """499 Extract compute value from the lammps library500 Parameters501 ----------502 id : string503 id of the compute504 style: {0, 1}505 0 - global data506 1 - per atom data507 type: {0, 1, 2}508 0 - scalar509 1 - vector510 2 - array511 length: int, optional. Default 0512 if `style` is 0 and `type` is 1 or 2, then `length` is the length513 of vector.514 width: int, optional. Default 0515 if `type` is 2, then `width` is the number of elements in each516 element along length.517 Returns518 -------519 val520 data computed by the fix depending on the chosen inputs521 """522 args = [id, style, type, length, width]523 self._send(command="extract_compute", data=args)524 return self._receive()525 def close(self):526 """527 Close the current lammps object528 Parameters529 ----------530 None531 Returns532 -------533 None534 """535 self._send(command="close")536 try:537 self._process.kill()538 except AttributeError:...
test_mpd.py
Source:test_mpd.py
...13 _send('OK MPD 1.2.3\n')14def _send(*x):15 'what shoud send to the client'16 _rwfile.readline.side_effect = x17def _receive(*a, **k):18 'what MPD should recieve from the client'19 _rwfile.write.assert_called_with(*a, **k)20def patch_record(m):21 global _send, _receive, _data22 _send = _receive = noop23 _data = []24 c = m._mpd25 r = c._rfile.readline26 def readline():27 line = r()28 _data.append('< ' + line)29 return line30 c._rfile.readline = readline31 w = c._wfile.write32 def write(x):33 _data.append('> ' + x)34 w(x)35 c._wfile.write = write36@pytest.fixture()37def mpd():38 try:39 m = MPD()40 m.connect('localhost', 6600)41 patch_record(m)42 yield m43 m.disconnect()44 except: # if connection to a real MPD fails, use mocked protocol replies45 m = MPD()46 patch_mock(m)47 m.connect('localhost', 6600)48 yield m49 finally:50 print(_rwfile.mock_calls)51 for x in _data:52 print(repr(x))53OK = 'OK\n'54def test_mpd_connect(mpd):55 assert mpd.timeout < 1056 assert mpd.idletimeout is None57 _send(OK)58 mpd.status()59 mpd._mpd.disconnect()60 _send('OK MPD foo\n', OK)61 mpd.status() # fails if it did not reconnect automatically62 _rwfile.write.side_effect = [ConnectionError] + [None] * 1063 _send('OK MPD foo\n', OK)64 mpd.status() # fails if it did not reconnect automatically65 _send(ConnectionError, 'OK MPD foo\n', OK)66 mpd.status() # fails if it did not reconnect automatically67@pytest.mark.xfail(strict=1)68def test_mpd_disconnect(mpd):69 mpd.disconnect()70 mpd.status() # must fail, because it's disconnected71def test_volume(mpd):72 _send('volume: 10\n', OK)73 v = mpd.volume()74 assert 0 <= v <= 10075 _receive('status\n')76 _send(OK)77 mpd.volume(42)78 _receive('setvol "42"\n')79 _send('volume: 42\n', OK)80 assert mpd.volume() == 4281 _receive('status\n')82 _send('volume: 42\n', OK, OK)83 mpd.volume('+3')84 _receive('setvol "45"\n')85 _send('volume: 45\n', OK)86 assert mpd.volume() == 42 + 387 _receive('status\n')88 _send('volume: 45\n', OK, OK)89 mpd.volume('-7')90 _receive('setvol "38"\n')91 _send('volume: 38\n', OK)92 assert mpd.volume() == 42 + 3 - 793 _receive('status\n')94def test_toggle_play(mpd):95 _send(OK)96 mpd.clear()97 _receive('clear\n')98 _send(OK)99 mpd.add('http://89.16.185.174:8003/stream')100 _receive('add "http://89.16.185.174:8003/stream"\n')101 _send('state: stop\n', OK)102 assert mpd.state() == 'stop'103 _receive('status\n')104 _send('state: stop\n', OK, OK)105 mpd.toggle_play()106 _receive('play\n')107 _send('state: play\n', OK)108 assert mpd.state() == 'play'109 _receive('status\n')110 _send('state: play\n', OK, OK)111 mpd.toggle_play()112 _receive('pause\n')113 _send('state: pause\n', OK)114 assert mpd.state() == 'pause'115 _receive('status\n')116 _send('state: pause\n', OK, OK)117 mpd.toggle_play()118 _receive('pause\n')119 _send('state: play\n', OK)120 assert mpd.state() == 'play'121 _receive('status\n')122 _send(OK)123 mpd.stop()124 _receive('stop\n')125 _send('state: stop\n', OK)126 assert mpd.state() == 'stop'127 _receive('status\n')128def test_save_playlist(mpd):129 pl = '#foo#'130 _send('ACK [50@0] {rm} No such playlist\n', OK)131 mpd.save_playlist(pl)132 _receive('save "' + pl + '"\n')133 _send(OK, OK)134 mpd.save_playlist(pl)135 _receive('save "' + pl + '"\n')136 _send('playlist: #foo#\n', OK)137 assert mpd.has_playlist(pl)138 _receive('listplaylists\n')139 _send(OK)140 mpd.del_playlist(pl)141 _receive('rm "' + pl + '"\n')142 _send(OK)143 assert not mpd.has_playlist(pl)144 _receive('listplaylists\n')145def test_load_playlist(mpd):146 pl = '#bar#'147 _send(OK)148 mpd.clear()149 _receive('clear\n')150 _send(OK)151 mpd.add('http://foo')152 _receive('add "http://foo"\n')153 _send(OK)154 mpd.add('http://bar')155 _receive('add "http://bar"\n')156 _send(OK, OK)157 mpd.save_playlist(pl)158 _receive('save "' + pl + '"\n')159 _send(OK)160 mpd.clear()161 _receive('clear\n')162 _send(OK)163 assert not mpd.playlist()164 _receive('playlist\n')165 _send('playlist: #bar#\n', OK, OK, OK)166 mpd.load_playlist(pl)167 _receive('load "' + pl + '"\n')168 _send('0:file: http://foo\n', '1:file: http://bar\n', OK)169 p = mpd.playlist()170 assert len(p) == 2171 _receive('playlist\n')172 _send(OK)173 mpd.del_playlist(pl)174 _receive('rm "' + pl + '"\n')175def test_playlist(mpd):176 _send(OK)177 mpd.clear()178 _receive('clear\n')179 pl = mpd.current_playlist()180 _send('playlistlength: 0\n', OK)181 assert len(pl) == 0182 _receive('status\n')183 urls = ['http://89.16.185.174:8003/stream',184 'http://89.16.185.174:8000/stream',185 'http://89.16.185.174:8004/stream']186 for u in urls:187 _send(OK)188 mpd.add(u)189 _receive('add "' + u + '"\n')190 _send('playlistlength: 3\n', OK)191 assert len(pl) == 3192 _receive('status\n')193 _send('playlistlength: 3\n', OK)194 pl_iter = iter(pl)195 _receive('status\n')196 # with title197 _send('file: ' + urls[0] + '\n', 'Pos: 0\n', 'Title: foo\n', OK)198 song = next(pl_iter)199 _receive('playlistinfo "0"\n')200 assert song['file'] == urls[0]201 assert song['pos'] == '0'202 assert 'title' in song203 # without title204 _send('file: ' + urls[1] + '\n', 'Pos: 1\n', OK, 'state: stop\n', OK, OK,205 'file: ' + urls[1] + '\n', 'Pos: 1\n', 'Title: bar\n', OK, OK)206 song = next(pl_iter)207 _receive('stop\n')208 assert song['file'] == urls[1]209 assert song['pos'] == '1'210 assert 'title' in song211 # title on second try212 _send('file: ' + urls[2] + '\n', 'Pos: 2\n', OK, 'state: play\n', 'song: 1\n', OK, OK,213 'file: ' + urls[2] + '\n', 'Pos: 2\n', OK,214 'file: ' + urls[2] + '\n', 'Pos: 2\n', 'Title: lorem ipsum\n', OK, OK)215 song = next(pl_iter)216 _receive('play "1"\n')217 assert song['file'] == urls[2]218 assert song['pos'] == '2'219 assert 'title' in song220 _send('state: stop\n', OK)221 assert mpd.state() == 'stop'222 _receive('status\n')223def test_playlist_find_next_single_album(mpd):224 _send(OK)225 mpd.clear()226 _receive('clear\n')227 pl = mpd.current_playlist()228 _send('playlistlength: 0\n', OK)229 assert len(pl) == 0230 _receive('status\n')231 urls = ['http://89.16.185.174:8003/stream',232 'http://89.16.185.174:8000/stream',233 'http://89.16.185.174:8004/stream']234 _send(OK, OK, OK)235 for u in urls:236 mpd.add(u)237 _send('state: stop\n', OK,238 'playlistlength: 3\n', OK,239 'Pos: 0\n', 'Album: foo\n', OK,240 'Pos: 1\n', 'Album: foo\n', OK,241 'Pos: 2\n', 'Album: foo\n', OK,242 )243 next = mpd.find_next('album')244 assert next is None245def test_playlist_find_next_two_albums(mpd):246 _send(OK)247 mpd.clear()248 _receive('clear\n')249 pl = mpd.current_playlist()250 _send('playlistlength: 0\n', OK)251 assert len(pl) == 0252 _receive('status\n')253 urls = ['http://89.16.185.174:8003/stream',254 'http://89.16.185.174:8000/stream',255 'http://89.16.185.174:8004/stream']256 _send(OK, OK, OK)257 for u in urls:258 mpd.add(u)259 _send('state: play\n', 'song: 1\n', OK,260 'playlistlength: 3\n', OK,261 'Pos: 1\n', 'Album: foo\n', OK,262 'Pos: 2\n', 'Album: bar\n', OK,263 )264 next = mpd.find_next('album')265 assert next == 2266def test_playlist_find_prev_single_album(mpd):267 _send(OK)268 mpd.clear()269 _receive('clear\n')270 pl = mpd.current_playlist()271 _send('playlistlength: 0\n', OK)272 assert len(pl) == 0273 _receive('status\n')274 urls = ['http://89.16.185.174:8003/stream',275 'http://89.16.185.174:8000/stream',276 'http://89.16.185.174:8004/stream']277 _send(OK, OK, OK)278 for u in urls:279 mpd.add(u)280 _send('state: stop\n', OK,281 'playlistlength: 3\n', OK,282 'Pos: 0\n', 'Album: foo\n', OK,283 'Pos: 1\n', 'Album: foo\n', OK,284 'Pos: 2\n', 'Album: foo\n', OK,285 )286 prev = mpd.find_prev('album')287 assert prev is None288def test_playlist_find_prev_two_albums(mpd):289 _send(OK)290 mpd.clear()291 _receive('clear\n')292 pl = mpd.current_playlist()293 _send('playlistlength: 0\n', OK)294 assert len(pl) == 0295 _receive('status\n')296 urls = ['http://89.16.185.174:8003/stream',297 'http://89.16.185.174:8000/stream',298 'http://89.16.185.174:8004/stream']299 _send(OK, OK, OK)300 for u in urls:301 mpd.add(u)302 _send('state: play\n', 'song: 2\n', OK,303 'playlistlength: 3\n', OK,304 'Pos: 2\n', 'Album: bar\n', OK,305 'Pos: 1\n', 'Album: foo\n', OK,306 'Pos: 0\n', 'Album: foo\n', OK,307 )308 prev = mpd.find_prev('album')309 assert prev == 0310def test_playlist_find_prev_three_albums(mpd):311 _send(OK)312 mpd.clear()313 _receive('clear\n')314 pl = mpd.current_playlist()315 _send('playlistlength: 0\n', OK)316 assert len(pl) == 0317 _receive('status\n')318 urls = ['http://89.16.185.174:8003/stream',319 'http://89.16.185.174:8000/stream',320 'http://89.16.185.174:8004/stream']321 _send(OK, OK, OK)322 for u in urls:323 mpd.add(u)324 _send(OK, OK, OK)325 for u in urls:326 mpd.add(u)327 _send('state: play\n', 'song: 4\n', OK,328 'playlistlength: 3\n', OK,329 'Pos: 4\n', 'Album: bar\n', OK,330 'Pos: 3\n', 'Album: bar\n', OK,331 'Pos: 2\n', 'Album: foo\n', OK,...
signals.py
Source:signals.py
1from django.db.models.signals import post_save, pre_delete2from django.contrib.auth.models import User3from django.dispatch import receiver4from .models import Profile,Relationship5@receiver(post_save, sender=User)6def post_save_create_profile(sender, instance, created, **kwargs):7 if created:8 Profile.objects.create(user=instance)9@receiver(post_save,sender=Relationship)10def profile_relationship_friends(sender,instance,created,**kwargs):11 _send=instance.sender12 _receive=instance.receiver13 if instance.status=="accepted":14 _send.friends.add(_receive.user)15 _receive.friends.add(_send.user)16 _send.save()17 _receive.save()18 19@receiver(pre_delete,sender=Relationship)20def remove_from_friends(sender,instance,**kwargs):21 _send=instance.sender22 _receive=instance.receiver23 _send.friends.remove(_receive.user)24 _receive.friends.remove(_send.user)25 _send.save()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!