Best Python code snippet using tempest_python
__init__.py
Source:__init__.py  
...91        internal_user = Role("internal_user", description="Placeholder description",92                             resources=default_resource_permissions_internal_user)93        db.session.add(internal_user)94    else:95        internal_user.set_resources(default_resource_permissions_internal_user)96    db.session.commit()97def initialize_default_resources_super_admin():98    """Initializes the default resources for a super admin user"""99    super_admin = Role.query.filter(Role.id == 2).first()100    if not super_admin:101        super_admin = Raole("super_admin", description="Placeholder description",102                           resources=default_resource_permissions_super_admin)103        db.session.add(super_admin)104    else:105        super_admin.set_resources(default_resource_permissions_super_admin)106    db.session.commit()107def initialize_default_resources_admin():108    """Initializes the default resources for an admin user"""109    admin = Role.query.filter(Role.id == 3).first()110    if not admin:111        admin = Role("admin", description="Placeholder description", resources=default_resource_permissions_admin)112        db.session.add(admin)113    else:114        admin.set_resources(default_resource_permissions_admin)115    db.session.commit()116def initialize_default_resources_app_developer():117    """Initializes the default resources for an app developer"""118    app_developer = Role.query.filter(Role.id == 4).first()119    if not app_developer:120        app_developer = Role("app_developer", description="Placeholder description",121                                  resources=default_resource_permissions_app_developer)122        db.session.add(app_developer)123    else:124        app_developer.set_resources(default_resource_permissions_app_developer)125    db.session.commit()126def initialize_default_resources_workflow_developer():127    """Initializes the default resources for a workflow developer"""128    workflow_developer = Role.query.filter(Role.id == 5).first()129    if not workflow_developer:130        workflow_developer = Role("workflow_developer", description="Placeholder description",131                                  resources=default_resource_permissions_workflow_developer)132        db.session.add(workflow_developer)133    else:134        workflow_developer.set_resources(default_resource_permissions_workflow_developer)135    db.session.commit()136def initialize_default_resources_workflow_operator():137    """Initializes the default resources for a workflow operator"""138    workflow_operator = Role.query.filter(Role.id == 6).first()139    if not workflow_operator:140        workflow_operator = Role("workflow_operator", description="Placeholder description",141                                 resources=default_resource_permissions_workflow_operator)142        db.session.add(workflow_operator)143    else:144        workflow_operator.set_resources(default_resource_permissions_workflow_operator)145    db.session.commit()146def get_roles_by_resource_permissions(resource_permission):147    r = resource_permission.resource148    permissions = resource_permission.permissions149    roles = []150    for permission in permissions:151        roles.extend(Role.query.join(Role.resources).join(Resource.permissions).filter(152            Resource.name == r, Permission.name == permission).all())153    return {role_obj.id for role_obj in roles}154def set_resources_for_role(role_name, resources):155    """Sets the resources a role is allowed to access.156    Args:157        role_name (str): The name of the role.158        resources (dict[resource:list[permission]): A dictionary containing the name of the resource, with the value159                being a list of permission names160    """161    r = Role.query.filter(Role.name == role_name).first()162    r.set_resources(resources)163def clear_resources_for_role(role_name):164    """Clears all of the resources that a role has access to.165    Args:166        role_name (str): The name of the role.167    """168    r = Role.query.filter(Role.name == role_name).first()169    r.resources = []170    db.session.commit()171def get_all_available_resource_actions():172    """Gets a list of all of the available resource actions173    Returns:174        (list[dict]): A list of dicts containing the resource name and the actions available for that resource175    """176    resource_actions = []...test_models.py
Source:test_models.py  
...10        # A base query set which returns *all* videos, even the deleted ones11        self.all_videos = models.CachedResource.objects.filter(type=models.CachedResource.VIDEO)12    def test_empty_iterable(self):13        """Cache should be updatable with empty iterable."""14        models.set_resources([], 'video')15        # There should be nothing in the cache16        self.assertEqual(self.videos.count(), 0)17    def test_simple_use(self):18        """Simple use of the cache should succeed."""19        models.set_resources([20            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}21        ], 'video')22        # We should now be able to query these values23        self.assertEqual(self.videos.count(), 2)24        self.assertEqual(self.videos.filter(data__x=5).first().key, 'foo')25    def test_expiry(self):26        """If a resource disappears, it should disappear from the cache."""27        models.set_resources([28            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}29        ], 'video')30        self.assertEqual(self.videos.count(), 2)31        models.set_resources([{'key': 'foo', 'x': 6}], 'video')32        self.assertEqual(self.videos.count(), 1)33        self.assertEqual(self.videos.filter(data__x=6).first().key, 'foo')34        self.assertEqual(self.videos.filter(data__x=5).count(), 0)35    def test_updated_at(self):36        """If a value is updated, the updated_at timestamp should be after created_at."""37        models.set_resources([{'key': 'foo', 'x': 5}], 'video')38        models.set_resources([{'key': 'foo', 'x': 5}], 'video')39        obj = self.videos.get(key='foo')40        self.assertGreater(obj.updated_at, obj.created_at)41    def test_iterable_resources(self):42        """update_resource_cache() should accept an iterable."""43        def resources():44            yield {'key': 'foo', 'x': 5}45            yield {'key': 'bar', 'x': 7}46        self.assertEqual(self.videos.count(), 0)47        models.set_resources(resources(), 'video')48        self.assertEqual(self.videos.count(), 2)49    def test_duplicate_keys(self):50        """If duplicate keys are in the resource iterable, the last one wins."""51        models.set_resources([52            {'key': 'foo', 'x': 5}, {'key': 'bar', 'x': 6}, {'key': 'foo', 'x': 7},53        ], 'video')54        obj = self.videos.get(key='foo')55        self.assertEqual(obj.data['x'], 7)56    def test_many_resources(self):57        """Adding many resources should be possible without taking an age."""58        def resources(count):59            # Generate the indices in random order60            for index in random.sample(range(count), k=count):61                yield {'key': f'resource_{index}', 'index': index}62        # Stress test the database. If there is a performance regression, we'll notice it when63        # running the tests. Add 10,000 resources then remove 5,000 of them.64        models.set_resources(resources(10000), 'video')65        models.set_resources(resources(5000), 'video')66        self.assertEqual(self.videos.count(), 5000)67    def test_soft_delete(self):68        """If a resource disappears, it should disappear from the cache but remain in the database69        with a non-NULL deleted_at time."""70        models.set_resources([71            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}72        ], 'video')73        self.assertEqual(self.videos.count(), 2)74        models.set_resources([{'key': 'foo', 'x': 6}], 'video')75        self.assertEqual(self.videos.count(), 1)76        self.assertEqual(self.all_videos.count(), 2)77        o = self.all_videos.get(key='bar')78        self.assertIsNotNone(o.deleted_at)79    def test_reinsertion(self):80        """If a resource disappears and re-appears, the deleted_at field should be None."""81        models.set_resources([82            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}83        ], 'video')84        models.set_resources([{'key': 'foo', 'x': 5}], 'video')85        models.set_resources([86            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}87        ], 'video')88        self.assertEqual(self.videos.count(), 2)89        self.assertEqual(self.all_videos.count(), 2)90        o = self.all_videos.get(key='bar')91        self.assertIsNone(o.deleted_at)92    def test_differing_types(self):93        """Setting two differnt types should not interfere."""94        models.set_resources([95            {'key': 'foo', 'x': 5}, {'key': 'bar', 'y': 7}96        ], 'video')97        models.set_resources([98            {'key': 'buzz', 'z': 5},99        ], 'channel')100        # We should now be able to query these values101        self.assertEqual(self.videos.count(), 2)102        self.assertEqual(self.videos.filter(data__x=5).first().key, 'foo')103        self.assertEqual(self.channels.count(), 1)104        self.assertEqual(self.channels.filter(data__z=5).first().key, 'buzz')105class VideoTest(TestCase):106    fixtures = ['mediaplatform_jwp/tests/fixtures/mediaitems.yaml']107    def setUp(self):108        self.video = models.Video.objects.first()109    def test_has_cached_resource(self):110        """A video has an associated cached resource """111        self.assertIsNotNone(self.video.resource)gusto.py
Source:gusto.py  
...39        return self.name + ' has resources: ' + str(self.resources) + ' and cards: ' + str(self.cards)40    def get_resources(self):41        return self.resources42        43    def set_resources(self, new_resources):44        self.resources = new_resources45        print self.resources46        47class Game: 48    # p1 -> single player 49    # player_names - an arr of str player names 50    def __init__(self, player_names):51        self.players = {} #dict of player_name -> player objects 52        for p_name in player_names: 53            new_p = Player(p_name) 54            self.players[p_name] = new_p 55            print "new player: " + new_p.to_string()56        print "Game started with players: " + str(self.players)57        58        59    def purchase_card(self, p_name, card): 60        61        player = Player(self.players.get(p_name))62        # print p63        # print p.to_string()64        65        p_resources = player.get_resources()66        print p_resources67        can_purchase = True 68        69        for col in card.price: 70            col_val = card.price[col]71            if col not in p_resources or p_resources[col] < col_val:72                can_purchase = False 73                74        if can_purchase: 75            new_p_resources = self.make_transaction(p_resources, card.price)76            player.resources = new_p_resources77            player.cards.add(card)78            print (p_name + ' was able to purchase ') 79            80        print (p_name + ' was not able to purchase ') 81        82        return 83        84    # def update_player_resources(self, p_name, new_resource_count): 85        86    #     player = self.players[p_name]87    #     player.set_resources(new_resource_count)88        89                90    # only call when we can make a card purchase 91    def make_transaction(self, p_resources, c_price):92        for c in c_price: 93            c_val = c_price[c] 94            p_resources[c] -= c_val 95            96        return p_resources 97        98        99        100        101        102       103new_game = Game(["p1"])  104p1 = new_game.players["p1"].set_resources({'Blue': 4, 'Red': 3})105# new_game.players["p1"] = {'Blue': 4, 'Red': 3}106p1 = new_game.players["p1"].set_resources({'Blue': 4, 'Red': 3})107# print p1.to_string()108c1 = Card(2, {'Blue': 2, 'Red': 2}, 'G')109 110        ...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!!
