Best Python code snippet using sure_python
test_old_api.py
Source:test_old_api.py  
...402    assert that({}).are_empty403    def fail_single():404        assert that((1,)).is_empty405    assert that(fail_single).raises('(1,) is not empty, it has 1 item')406    def fail_plural():407        assert that((1, 2)).is_empty408    assert that(fail_plural).raises('(1, 2) is not empty, it has 2 items')409def test_that_something_is_empty_raises():410    "that(something_not_iterable).is_empty and that(something_not_iterable).are_empty raises"411    obj = object()412    def fail():413        assert that(obj).is_empty414        assert False, 'should not reach here'415    assert that(fail).raises('%r is not iterable' % obj)416def test_that_something_iterable_matches_another():417    "that(something_iterable).matches(another_iterable)"418    # types must be unicode in py3, bute bytestrings in py2419    KlassOne = type('KlassOne' if PY3 else b'KlassOne', (object,), {})420    KlassTwo = type('KlassTwo' if PY3 else b'KlassTwo', (object,), {})...sessions.py
Source:sessions.py  
1import argparse2import junkdrawer3import os4import playsound5import random6import signal7import sqlite38import sys9import threading10import time11import yaml12home_dir    = os.environ['HOME']13audio_dir   = f'{home_dir}/lib/audio'14class session(object):15  def __init__(self, database=f'{os.getenv("HOME")}/.config/sessions.sqlite'):16    args = self.cli_args()17    if args.database is not None:18      database = args.database19    if not os.path.isfile(database):20      print(f'Please create database: {database}')21      sys.exit(1)22    try:23      self._dbh = sqlite3.connect(database)24    except sqlite3.OperationalError as e:25      print(f'Error connecting to database: {e}')26      sys.exit(2)27    self.database = database28    # Mutable DB variables29    self._setters = [ 'sessions_owed' ]30    # By default, green light is active31    self._green = 132    # Allow --nogreen to disable any green light potential33    if args.nogreen:34      self._green = 035    # Flag to track if there was a chance to finish this session36    self.cum_chance = 037    # Check to see how many sessions have been done in the cooldown window38    self.cooldown = self.check_cooldown()39    # only allow 1 'bonus' session40    if self.cooldown > 1:41      print('Only one bonus session allowed. Wait for cooldown.')42      sys.exit(1)43    # get the min / max number of edges from DB44    edges_min = int(self.get('edges_min'))45    edges_max = int(self.get('edges_max'))46    # increase min/max edges if doing a 'bonus' session47    if self.cooldown > 0:48      print('Bonus Session. Will not decrement session counter.')49      edges_min += 350      edges_max += 351    spread = abs(int(edges_min - edges_max))52    plus_minus = int(spread / 2)53    # If the spread is odd; e.g. 5, randomly pick 2 or 3 as the plus_minus54    if spread > (plus_minus * 2) and random.randint(0, 1) == 1:55      plus_minus = plus_minus + 156    # set edges as middle value, then randomly add / remove57    # edges to favor the middle, but allow for the extremes58    edges = edges_min + int(spread / 2)59    for foo in range(1, plus_minus):60      # Randomly add an edge61      if random.randint(0, 2) == 1:62        edges = edges + 163      # Randomly remove an edge64      if random.randint(0, 2) == 1:65        edges = edges - 166    # set the session edge count67    self.edges_left = edges68    # Initialize counters69    self.edges_fail = 070    self.edges_done = 071    self.audio_dir = audio_dir72    self.goal_min = int(self.get('goal_min'))73    self.goal_max = int(self.get('goal_max'))74    # Allow --edges to override rolled edges; but only if more are requested75    if args.edges > self.edges_left:76      self.edges_left = args.edges77    # Log the session in the DB78    self.session_id = self.log_session()79    signal.signal(signal.SIGINT, self.sig_handler)80  def sig_handler(self, *args):81    self.end_session()82    print()83    print('Session Aborted!', file=sys.stderr)84    print()85    if self.edges_left > 0:86      self.add('sessions_owed')87    self._dbh.close()88    sys.exit(1)89  def log_session(self):90    # Get a session id91    query = 'insert into sessions (edges) values (?)'92    sth = self._dbh.cursor()93    sth.execute(query, (self.edges_left,))94    session_id = sth.lastrowid95    self._dbh.commit()96    return session_id97  def check_cooldown(self):98    # get the cooldown window99    window = str(self.get('cooldown_window'))100    # return number of sessions done in the cooldown window101    query = f'select count(*) from sessions where time > datetime(?, ?)'102    sth = self._dbh.cursor()103    sth.execute(query, ('now', f'-{window}'))104    count = int(sth.fetchone()[0])105    return count106  def end_session(self):107    left_plural = 'edge' if self.edges_left == 1 else 'edges'108    done_plural = 'edge' if self.edges_done == 1 else 'edges'109    fail_plural = 'edge' if self.edges_fail == 1 else 'edges'110    print()111    print(f'{self.edges_fail} {fail_plural} failed')112    print(f'{self.edges_done} {done_plural} done')113    print(f'{self.edges_left} {left_plural} left')114    query = ''' update sessions set cum_chance = ?, fail = ?,115                  done =?, left = ? where id = ?'''116    sth = self._dbh.cursor()117    sth.execute(query, (118            self.cum_chance,119            self.edges_fail,120            self.edges_done,121            self.edges_left,122            self.session_id,123          ))124    self._dbh.commit()125  def do_session(self):126    while self.edges_left > 0:127      elapsed = self.stroke()128      self.log_edge(elapsed)129      time.sleep(random.randint(3, 5))130      self.judge_edge(elapsed)131      self.edges_done += 1132      # Cool down133      time.sleep(random.randint(134                        int(self.get('cooldown_min')),135                        int(self.get('cooldown_max')),136                      ))137    print('  You may stop stroking your cock.')138    sound = self.choose_sound(f'{self.audio_dir}/stop')139    self.play_sound(sound)140    # don't decrement sessions_owed if on cooldown141    if self.cooldown == 0:142      self.sub('sessions_owed')143    # Current state of green light -- setting may have changed during play144    owed = int(self.get('sessions_owed'))145    green = int(self.get('enable_green')) and self._green146    if green and owed <= 0:147      self.finish()148    self.end_session()149    self._dbh.close()150  def get(self, key):151    query = 'select val from settings where key = ?'152    sth = self._dbh.cursor()153    sth.execute(query, (key,))154    val = sth.fetchone()155    if val is None:156      print(f'Value for key not stored: {key}', file=sys.stderr)157      return None158    else:159      return val[0]160  def set(self, key, val):161    query = 'update settings set val = ? where key = ?'162    sth = self._dbh.cursor()163    if key in self._setters:164      sth.execute(query, (val, key))165      self._dbh.commit()166    else:167      raise NameError(f'Key not accepted in set() method: {key}')168  def add(self, key, val = 1):169    temp = int(self.get(key))170    self.set(key, temp + val)171  def sub(self, key, val = 1):172    temp = int(self.get(key))173    self.set(key, temp - val)174  def finish(self):175    # Flip 3 coins176    coin1 = random.randint(0, 1)177    coin2 = random.randint(0, 1)178    coin3 = random.randint(0, 1)179    if coin1 and coin2 and coin3:180      print()181      print('Continue stroking your cock.')182      sound = self.choose_sound(f'{self.audio_dir}/continue')183      self.play_sound(sound, 0)184      # Fake out delay185      time.sleep(random.randint(3, 30))186      print('  GREEN LIGHT!')187      sound = self.choose_sound(f'{self.audio_dir}/finish')188      self.play_sound(sound, 0)189      time.sleep(random.randint(190                        int(self.get('green_min')),191                        int(self.get('green_max')),192                      ))193      sound = self.choose_sound(f'{self.audio_dir}/stop')194      self.play_sound(sound, 0)195      print()196      print('    Hands off your cock!')197      print()198      self.cum_chance = 1199  def stroke(self):200    if self.edges_done == 0:201      print('Start stroking your cock.')202      sound = self.choose_sound(f'{self.audio_dir}/start')203      self.play_sound(sound, 0)204    else:205      print()206      print('Continue stroking your cock.')207      sound = self.choose_sound(f'{self.audio_dir}/continue')208      self.play_sound(sound, 0)209    time.sleep(junkdrawer.fuzzy_weight(210                            int(self.get('stroke_min')),211                            int(self.get('stroke_max')),212                            int(self.get('stroke_skew')),213                          ))214    for null in range(0, 5):215      if random.randint(1, 8) == 1:216        sound = self.choose_sound(f'{self.audio_dir}/laugh')217        self.play_sound(sound, 0)218        time.sleep(random.randint(219                          int(self.get('stroke_add_min')),220                          int(self.get('stroke_add_max'))))221    print("  Don't Think. Just Edge.")222    sound = self.choose_sound(f'{self.audio_dir}/edge')223    self.play_sound(sound, 0)224    start = time.time()225    input("    Press 'Enter' once you get to the edge.")226    print("  Hands off your cock")227    sound = self.choose_sound(f'{self.audio_dir}/cooldown')228    self.play_sound(sound, 0)229    elapsed = time.time() - start230    return elapsed231  def log_edge(self, elapsed):232    query = 'insert into edges (session_id, to_edge, max) values (?, ?, ?)'233    sth = self._dbh.cursor()234    sth.execute(query, (self.session_id,235                        elapsed,236                        self.goal_max,237                      ))238    self._dbh.commit()239  def judge_edge(self, elapsed):240    if elapsed > self.goal_max:241      sound = self.choose_sound(f'{self.audio_dir}/slow')242      self.play_sound(sound, 0)243      self.edges_fail += 1244      print("    Too Slow. Try Again.")245      if self.edges_fail > 2:246        self.add('sessions_owed')247    else:248      sound = self.choose_sound(f'{self.audio_dir}/good')249      self.play_sound(sound, 0)250      self.edges_left -= 1251      print("    Good Boy!")252    if (elapsed > self.goal_min and elapsed < self.goal_max):253      self.goal_max = elapsed254  def cli_args(self):255    parser = argparse.ArgumentParser(256              description='A script to do edging sessions',257              epilog='-=-= Have fun. :D =-=-',258              formatter_class=argparse.MetavarTypeHelpFormatter)259    parser.add_argument(260      '--database',261      default=None,262      type=str,263      help='Path to the sqlite3 database to use',264    )265    parser.add_argument(266      '--nogreen',267      action='store_true',268      default=False,269      help='Disable green light'270    )271    parser.add_argument(272      '--edges',273      default=0,274      type=int,275      help='Specify the number of edges',276    )277    parser.add_argument(278      '--test',279      action='store_true',280      default=False,281      help="Don't play sounds, wait, or log sessions and edges",282    )283    return parser.parse_args()284  def choose_sound(self, directory):285    if os.path.isdir(directory):286      filename = ''287      while not os.path.isfile(f'{directory}/{filename}'):288        filename = random.choice(os.listdir(directory))289      return f'{directory}/{filename}'290    return None291  def play_sound(self, sound, blocking = 0):292    if sound is None:293      return294    if blocking == 1:295      playsound.playsound(sound)296    else:297      thread = threading.Thread(target = playsound.playsound, args = (sound,))298      thread.start()...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!!
