How to use set_auth method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_app.py

Source: test_app.py Github

copy
1import os
2import unittest
3import json
4from flask_sqlalchemy import SQLAlchemy
5from app import app
6from models import db, db_drop_and_create_all, setup_db, Movie, Actor
7from auth import AuthError, requires_auth
8from sqlalchemy import Column, String, Integer, DateTime
9import logging
10from configparser import ConfigParser
11
12
13database_name = "database_test.db"
14project_dir = os.path.dirname(os.path.abspath(__file__))
15database_path = "sqlite:///{}".format(os.path.join(project_dir, database_name))
16
17assistant_token = os.getenv('ASSISTANT_JWT')
18director_token = os.getenv('DIRECTOR_JWT')
19producer_token = os.getenv('PRODUCER_JWT')
20
21
22def set_auth(role):
23    if role == 'assistant':
24        return {
25            "Content-Type": "application/json",
26            "Authorization": "Bearer {}".format(assistant_token)
27            }
28    elif role == 'director':
29        return {
30            "Content-Type": "application/json",
31            'Authorization': 'Bearer {}'.format(director_token)
32            }
33    elif role == 'producer':
34        return {
35            "Content-Type": "application/json",
36            'Authorization': 'Bearer {}'.format(producer_token)
37            }
38
39
40class testCase(unittest.TestCase):
41
42    def setUp(self):
43        app.config['TESTING'] = True
44        app.config['WTF_CSRF_ENABLED'] = False
45        app.config['DEBUG'] = False
46        app.config['SQLALCHEMY_DATABASE_URI'] = database_path
47        self.app = app.test_client()
48        db.drop_all()
49        db.create_all()
50
51    def tearDown(self):
52        """Executed after reach test"""
53        pass
54
55    def test_get_movies_assistant(self):
56        res = self.app.get('/movies', headers=set_auth('assistant'))
57        self.assertEqual(res.status_code, 200)
58
59    def test_get_movies_director(self):
60        res = self.app.get('/movies', headers=set_auth('director'))
61        self.assertEqual(res.status_code, 200)
62
63    def test_get_movies_producer(self):
64        res = self.app.get('/movies', headers=set_auth('producer'))
65        self.assertEqual(res.status_code, 200)
66
67    def test_get_movies_fail(self):
68        res = self.app.get('/movies', headers=set_auth(''))
69        self.assertEqual(res.status_code, 401)
70
71    def test_post_movie_assistant(self):
72        data = {
73            "title": "test_title"
74        }
75        res = self.app.post('/movies', json=data,
76                            headers=set_auth('assistant'))
77        self.assertEqual(res.status_code, 401)
78
79    def test_post_movie_director(self):
80        data = {
81            "title": "test_title"
82        }
83        res = self.app.post('/movies', json=data, headers=set_auth('director'))
84        self.assertEqual(res.status_code, 401)
85
86    def test_post_movie_producer(self):
87        data = {
88            "title": "test_title"
89        }
90        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
91        self.assertEqual(res.status_code, 200)
92        self.assertEqual(res.get_json()['success'], True)
93
94    def test_post_movie_fail(self):
95        res = self.app.post('/movies', json={}, headers=set_auth('producer'))
96        self.assertEqual(res.status_code, 422)
97        self.assertEqual(res.get_json()['success'], False)
98
99    def test_patch_movie_assistant(self):
100        data = {
101            "title": "test_title"
102        }
103        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
104
105        updated_data = {
106            "title": "updated_title"
107        }
108
109        res = self.app.patch('/movies/1', json=updated_data,
110                             headers=set_auth('assistant'))
111        self.assertEqual(res.status_code, 401)
112
113    def test_patch_movie_director(self):
114        data = {
115            "title": "test_title"
116        }
117        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
118
119        updated_data = {
120            "title": "updated_title"
121        }
122
123        res = self.app.patch('/movies/1', json=updated_data,
124                             headers=set_auth('director'))
125        self.assertEqual(res.status_code, 200)
126
127    def test_patch_movie_producer(self):
128        data = {
129            "title": "test_title"
130        }
131        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
132
133        updated_data = {
134            "title": "updated_title"
135        }
136
137        res = self.app.patch('/movies/1', json=updated_data,
138                             headers=set_auth('producer'))
139        self.assertEqual(res.status_code, 200)
140        self.assertEqual(res.get_json()['success'], True)
141
142    def test_patch_movie_fail(self):
143        data = {
144            "title": "test_title"
145        }
146        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
147
148        res = self.app.patch('/movies/100000', json={},
149                             headers=set_auth('producer'))
150
151        self.assertEqual(res.status_code, 404)
152        self.assertEqual(res.get_json()['success'], False)
153
154    def test_delete_movie_fail(self):
155        res = self.app.delete('/movies/1000000', headers=set_auth('producer'))
156        self.assertEqual(res.status_code, 404)
157
158    def test_delete_movie_assistant(self):
159        data = {
160            "title": "test_title"
161        }
162        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
163
164        res = self.app.delete('/movies/1', headers=set_auth('assistant'))
165        self.assertEqual(res.status_code, 401)
166
167    def test_delete_movie_director(self):
168        data = {
169            "title": "test_title"
170        }
171        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
172
173        res = self.app.delete('/movies/1', headers=set_auth('director'))
174        self.assertEqual(res.status_code, 401)
175
176    def test_delete_movie_producer(self):
177        data = {
178            "title": "test_title"
179        }
180        res = self.app.post('/movies', json=data, headers=set_auth('producer'))
181
182        res = self.app.delete('/movies/1', headers=set_auth('producer'))
183        self.assertEqual(res.status_code, 200)
184
185    def test_delete_movies_fail(self):
186        res = self.app.delete('/movies/1', headers=set_auth(''))
187        self.assertEqual(res.status_code, 401)
188
189    # Actor Tests
190    def test_get_actors_assistant(self):
191        res = self.app.get('/actors', headers=set_auth('assistant'))
192        self.assertEqual(res.status_code, 200)
193
194    def test_get_actors_director(self):
195        res = self.app.get('/actors', headers=set_auth('director'))
196        self.assertEqual(res.status_code, 200)
197
198    def test_get_actors_producer(self):
199        res = self.app.get('/actors', headers=set_auth('producer'))
200        self.assertEqual(res.status_code, 200)
201
202    def test_get_actor_fail(self):
203        res = self.app.get('/actors', headers=set_auth(''))
204        self.assertEqual(res.status_code, 401)
205
206    def test_post_actor_assistant(self):
207        data = {
208            "name": "updated_name",
209            "gender": "female",
210            "age": 30
211        }
212        res = self.app.post('/actors', json=data,
213                            headers=set_auth('assistant'))
214        self.assertEqual(res.status_code, 401)
215
216    def test_post_actor_director(self):
217        data = {
218            "name": "updated_name",
219            "gender": "female",
220            "age": 30
221        }
222        res = self.app.post('/actors', json=data, headers=set_auth('director'))
223        self.assertEqual(res.status_code, 200)
224
225    def test_post_actor_producer(self):
226        data = {
227            "name": "updated_name",
228            "gender": "female",
229            "age": 30
230        }
231        res = self.app.post('/actors', json=data, headers=set_auth('producer'))
232        self.assertEqual(res.status_code, 200)
233        self.assertEqual(res.get_json()['success'], True)
234
235    def test_post_actors_fail(self):
236        res = self.app.post('/actors', json={}, headers=set_auth('producer'))
237        self.assertEqual(res.status_code, 422)
238        self.assertEqual(res.get_json()['success'], False)
239
240    def test_patch_actor_assistant(self):
241        data = {
242            "name": "test_name",
243            "gender": "female",
244            "age": 30
245        }
246        res = self.app.post('/actors', json=data, headers=set_auth('producer'))
247
248        updated_data = {
249            "name": "updated_name",
250            "gender": "female",
251            "age": 35
252        }
253
254        res = self.app.patch('/actors/1', json=updated_data,
255                             headers=set_auth('assistant'))
256        self.assertEqual(res.status_code, 401)
257
258    def test_patch_actor_director(self):
259        data = {
260            "name": "test_name",
261            "gender": "female",
262            "age": 30
263        }
264        res = self.app.post('/actors', json=data, headers=set_auth('director'))
265
266        updated_data = {
267            "name": "updated_name",
268            "gender": "female",
269            "age": 35
270        }
271
272        res = self.app.patch('/actors/1', json=updated_data,
273                             headers=set_auth('director'))
274        self.assertEqual(res.status_code, 200)
275        self.assertEqual(res.get_json()['success'], True)
276
277    def test_patch_actor_producer(self):
278        data = {
279            "name": "test_name",
280            "gender": "female",
281            "age": 30
282        }
283        res = self.app.post('/actors', json=data, headers=set_auth('producer'))
284
285        updated_data = {
286            "name": "updated_name",
287            "gender": "female",
288            "age": 35
289        }
290
291        res = self.app.patch('/actors/1', json=updated_data,
292                             headers=set_auth('producer'))
293        self.assertEqual(res.status_code, 200)
294        self.assertEqual(res.get_json()['success'], True)
295
296    def test_patch_actor_fail(self):
297        data = {
298            "name": "test_name",
299            "gender": "female",
300            "age": 30
301        }
302        res = self.app.post('/actors', json=data, headers=set_auth('producer'))
303
304        res = self.app.patch('/actors/100000', json={},
305                             headers=set_auth('producer'))
306
307        self.assertEqual(res.status_code, 404)
308        self.assertEqual(res.get_json()['success'], False)
309
310    def test_delete_actor_assistant(self):
311        data = {
312            "name": "test_name",
313            "gender": "female",
314            "age": 30
315        }
316        res = self.app.post('/actors', json=data,
317                            headers=set_auth('assistant'))
318
319        res = self.app.delete('/actors/1', headers=set_auth('assistant'))
320        self.assertEqual(res.status_code, 401)
321
322    def test_delete_actor_director(self):
323        data = {
324            "name": "test_name",
325            "gender": "female",
326            "age": 30
327        }
328        res = self.app.post('/actors', json=data, headers=set_auth('director'))
329
330        res = self.app.delete('/actors/1', headers=set_auth('director'))
331        self.assertEqual(res.status_code, 200)
332
333    def test_delete_actor_producer(self):
334        data = {
335            "name": "test_name",
336            "gender": "female",
337            "age": 30
338        }
339        res = self.app.post('/actors', json=data, headers=set_auth('producer'))
340
341        res = self.app.delete('/actors/1', headers=set_auth('producer'))
342        self.assertEqual(res.status_code, 200)
343
344    def test_delete_actor_fail(self):
345        logging.info("Intentionally Missing Auth Header (see below)")
346        res = self.app.delete('/actors/1', headers=set_auth(''))
347        self.assertEqual(res.status_code, 401)
348
349
350if __name__ == '__main__':
351    unittest.main()
352
Full Screen

discordlist.py

Source: discordlist.py Github

copy
1from discord.ext import commands
2import discordlists
3
4
5class DiscordListsPost(commands.Cog):
6    def __init__(self, client):
7        self.client = client
8        self.api = discordlists.Client(self.client)  # Create a Client instance
9        self.api.set_auth("bladebotlist.xyz", "U7RUFhtzY0f18Zx.wKZB8zvJ0xdXAAC.vxIfcICRVssUrlp")
10        self.api.set_auth("space-bot-list.xyz", "7X-OoJ7alP9JoF-RFVRObjviMEngmnEMSBVoqdd9idovIBphtp")
11        self.api.set_auth("discordbotlist.com", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0IjoxLCJpZCI6Ijc5MDUyNTk4NTI2NjU5NzkxOCIsImlhdCI6MTYyMjMwNjIwMn0.UJkW-4MXehH30o2Qn4pOXZlI702cGi1GQ-ZH6KCd9SU")
12        self.api.set_auth("botsfordiscord.com", "a95af6049919ec81f2ce4442a2e44d5a5dca411e93ca01a3577f6c5856adff6480065b97c2e41892fbbf0b9883b20e98516c39742072f26a1bb57e4ec73c5157")
13        self.api.set_auth("discord.bots.gg", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGkiOnRydWUsImlkIjoiNDg5NjgyNjc2MTU3MTIwNTEzIiwiaWF0IjoxNjIyMzA2NDU0fQ.AWdiq_6yJYIrA6FyqZYQxijOIMe5e6u0UZhg10m3K1w")
14        self.api.set_auth("infinitybotlist.com", "dQRUj3HYDxsHssTI4WrBtTikMcD1wOghuubGhAwPmB4DuTORuQz8Ub7u2Le7ko4EzbpGTK92nf28Z5ZUL71rd7zr3ms7icq9QZZw")
15        #self.api.set_auth("discordlist.space", "942292990d0fe954c70e539429ee8ac6e3cb55100bcfb798acb6b3046120c233f243b2417b6fe49e21303c2cac30860a")
16        self.api.set_auth("disforge.com", "f53e565beed654b2de49151a082dc9a3bbd146aef30efb81226089740b97f02e")
17        self.api.start_loop()
18
19    @commands.command()
20    @commands.is_owner()
21    async def post(self, ctx: commands.Context):
22        """
23        Manually posts guild count using discordlists.py (BotBlock)
24        """
25        try:
26            result = await self.api.post_count()
27        except Exception as e:
28            await ctx.send("Request failed: `{}`".format(e))
29            return
30
31        await ctx.send("Successfully manually posted server count ({:,}) to {:,} lists."
32                       "\nFailed to post server count to {:,} lists.".format(self.api.server_count,
33                                                                             len(result["success"].keys()),
34                                                                             len(result["failure"].keys())))
35
36    @commands.command()
37    @commands.is_owner()
38    async def get(self, ctx: commands.Context, bot_id: int = None):
39        """
40        Gets a bot using discordlists.py (BotBlock)
41        """
42        if bot_id is None:
43            bot_id = self.client.user.id
44        try:
45            result = (await self.api.get_bot_info(bot_id))[1]
46        except Exception as e:
47            await ctx.send("Request failed: `{}`".format(e))
48            return
49
50        await ctx.send("Bot: {}#{} ({})\nOwners: {}\nServer Count: {}".format(
51            result['username'], result['discriminator'], result['id'],
52            ", ".join(result['owners']) if result['owners'] else "Unknown",
53            "{:,}".format(result['server_count']) if result['server_count'] else "Unknown"
54        ))
55
56
57
58def setup(client):
59    client.add_cog(DiscordListsPost(client))
Full Screen

remote.py

Source: remote.py Github

copy
1"""
2# Copyright 2016-2022 The Johns Hopkins University Applied Physics Laboratory
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""
16from intern.remote import Remote
17from intern.resource.boss.resource import *
18from intern.service.boss.project import ProjectService
19from intern.service.boss.metadata import MetadataService
20from intern.service.boss.volume import VolumeService
21from intern.service.boss.v1.volume import CacheMode
22import warnings
23
24
25CONFIG_PROJECT_SECTION = 'Project Service'
26CONFIG_METADATA_SECTION = 'Metadata Service'
27CONFIG_VOLUME_SECTION = 'Volume Service'
28CONFIG_PROTOCOL = 'protocol'
29# CONFIG_HOST example: api.theboss.io
30CONFIG_HOST = 'host'
31CONFIG_TOKEN = 'token'
32
33LATEST_VERSION = 'v1'
34
35class BossRemote(Remote):
36    """
37    Remote provides an SDK to the Boss API.
38
39    Attributes:
40        _token_project (string): Django Framework token for auth to the
41            project service.
42        _token_metadata (string): Django Framework token for auth to the
43            metadata service.
44        _token_volume (string): Django Framework token for auth to the
45            volume service.
46    """
47
48    def __init__(self, cfg_file_or_dict=None, version=None):
49        """
50        Constructor.
51
52        If not config arguments are passed in, ~/.intern/intern.cfg is read by
53        default.  Config data is in INI format.  If both cfg_file and cfg_str
54        are passed in, the value in cfg_str is used.
55
56        Args:
57            version (optional[string]): Version of Boss API to use.
58            cfg_file_or_dict (optional[string|dict]): Path to config file in
59                INI format or a dict of config parameters.
60
61        Raises:
62            (FileNotFoundError): if can't load given config file.
63            (KeyError): if given invalid version.
64        """
65        Remote.__init__(self, cfg_file_or_dict)
66
67        if version is None:
68            version = LATEST_VERSION
69
70        # Init the services
71        self._init_project_service(version)
72        self._init_metadata_service(version)
73        self._init_volume_service(version)
74
75    def __repr__(self):
76        """
77        Stringify the Remote.
78
79        Returns a representation of the BossRemote that lists the host.
80        """
81        return "<intern.remote.BossRemote [" + self._config['Default']['host'] + "]>"
82
83    def _init_project_service(self, version):
84        """
85        Method to initialize the Project Service from the config data
86
87        Args:
88            version (string): Version of Boss API to use.
89
90        Returns:
91            None
92
93        Raises:
94            (KeyError): if given invalid version.
95        """
96        project_cfg = self._load_config_section(CONFIG_PROJECT_SECTION)
97        self._token_project = project_cfg[CONFIG_TOKEN]
98        proto = project_cfg[CONFIG_PROTOCOL]
99        host = project_cfg[CONFIG_HOST]
100
101        self._project = ProjectService(host, version)
102        self._project.base_protocol = proto
103        self._project.set_auth(self._token_project)
104
105    def _init_metadata_service(self, version):
106        """
107        Method to initialize the Metadata Service from the config data
108
109        Args:
110            version (string): Version of Boss API to use.
111
112        Returns:
113            None
114
115        Raises:
116            (KeyError): if given invalid version.
117        """
118        metadata_cfg = self._load_config_section(CONFIG_METADATA_SECTION)
119        self._token_metadata = metadata_cfg[CONFIG_TOKEN]
120        proto = metadata_cfg[CONFIG_PROTOCOL]
121        host = metadata_cfg[CONFIG_HOST]
122
123        self._metadata = MetadataService(host, version)
124        self._metadata.base_protocol = proto
125        self._metadata.set_auth(self._token_metadata)
126
127    def _init_volume_service(self, version):
128        """
129        Method to initialize the Volume Service from the config data
130
131        Args:
132            version (string): Version of Boss API to use.
133
134        Returns:
135            None
136
137        Raises:
138            (KeyError): if given invalid version.
139        """
140        volume_cfg = self._load_config_section(CONFIG_VOLUME_SECTION)
141        self._token_volume = volume_cfg[CONFIG_TOKEN]
142        proto = volume_cfg[CONFIG_PROTOCOL]
143        host = volume_cfg[CONFIG_HOST]
144
145        self._volume = VolumeService(host, version)
146        self._volume.base_protocol = proto
147        self._volume.set_auth(self._token_volume)
148
149    def _load_config_section(self, section_name):
150        """
151        Method to load the specific Service section from the config file if it
152        exists, or fall back to the default
153
154        Args:
155            section_name (str): The desired service section name
156
157        Returns:
158            (dict): the section parameters
159        """
160        if self._config.has_section(section_name):
161            # Load specific section
162            section = dict(self._config.items(section_name))
163        elif self._config.has_section("Default"):
164            # Load Default section
165            section = dict(self._config.items("Default"))
166        else:
167            raise KeyError((
168                "'{}' was not found in the configuration file and no default " +
169                "configuration was provided."
170            ).format(section_name))
171
172        # Make sure section is valid
173        if "protocol" in section and "host" in section and "token" in section:
174            return section
175        else:
176            raise KeyError(
177                "Missing values in configuration data. " +
178                "Must contain: protocol, host, token"
179            )
180
181    @property
182    def token_project(self):
183        """
184        Returns the current token
185        """
186        return self._token_project
187
188    @token_project.setter
189    def token_project(self, value):
190        self._token_project = value
191        self.project_service.set_auth(self._token_project)
192
193    @property
194    def token_metadata(self):
195        """
196        Returns metadata for the current token
197        """
198        return self._token_metadata
199
200    @token_metadata.setter
201    def token_metadata(self, value):
202        self._token_metadata = value
203        self.metadata_service.set_auth(self._token_metadata)
204
205    @property
206    def token_volume(self):
207        """
208        Get the current token volume
209        """
210        return self._token_volume
211
212    @token_volume.setter
213    def token_volume(self, value):
214        self._token_volume = value
215        self.volume_service.set_auth(self._token_volume)
216
217    def list_groups(self, filtr=None):
218        """
219        Get the groups the logged in user is a member of.
220
221        Optionally filter by 'member' or 'maintainer'.
222
223        Args:
224            filtr (optional[string|None]): ['member'|'maintainer']
225
226        Returns:
227            (list[string]): List of group names.
228
229        Raises:
230            requests.HTTPError on failure.
231        """
232        self.project_service.set_auth(self._token_project)
233        return self.project_service.list_groups(filtr)
234
235    def get_group(self, name, user_name=None):
236        """
237        Get information on the given group or whether or not a user is a member
238        of the group.
239
240        Args:
241            name (string): Name of group to query.
242            user_name (optional[string]): Supply None if not interested in
243            determining if user is a member of the given group.
244
245        Returns:
246            (mixed): Dictionary if getting group information or bool if a user
247                name is supplied.
248
249        Raises:
250            requests.HTTPError on failure.
251        """
252        self.project_service.set_auth(self._token_project)
253        return self.project_service.get_group(name, user_name)
254
255    def create_group(self, name):
256        """
257        Create a new group.
258
259        Args:
260            name (string): Name of the group to create.
261
262        Returns:
263            (bool): True on success.
264
265        Raises:
266            requests.HTTPError on failure.
267        """
268        self.project_service.set_auth(self._token_project)
269        return self.project_service.create_group(name)
270
271    def delete_group(self, name):
272        """
273        Delete given group.
274
275        Args:
276            name (string): Name of group.
277
278        Returns:
279            (bool): True on success.
280
281        Raises:
282            requests.HTTPError on failure.
283        """
284        self.project_service.set_auth(self._token_project)
285        return self.project_service.delete_group(name)
286
287    def list_group_members(self, name):
288        """
289        Get the members of a group.
290
291        Args:
292            name (string): Name of group to query.
293
294        Returns:
295            (list[string]): List of member names.
296
297        Raises:
298            requests.HTTPError on failure.
299        """
300        self.project_service.set_auth(self._token_project)
301        return self.project_service.list_group_members(name)
302
303    def add_group_member(self, grp_name, user):
304        """
305        Add the given user to the named group.
306
307        Both group and user must already exist for this to succeed.
308
309        Args:
310            name (string): Name of group.
311            user_name (string): User to add to group.
312
313        Raises:
314            requests.HTTPError on failure.
315        """
316        self.project_service.set_auth(self._token_project)
317        self.project_service.add_group_member(grp_name, user)
318
319    def delete_group_member(self, grp_name, user):
320        """
321        Delete the given user to the named group.
322
323        Both group and user must already exist for this to succeed.
324
325        Args:
326            name (string): Name of group.
327            user_name (string): User to delete from the group.
328
329        Raises:
330            requests.HTTPError on failure.
331        """
332        self.project_service.set_auth(self._token_project)
333        self.project_service.delete_group_member(grp_name, user)
334
335    def get_is_group_member(self, grp_name, user):
336        """
337        Check if the given user is a member of the named group.
338
339        Note that a group maintainer is not considered a member unless the
340        user is also explicitly added as a member.
341
342        Args:
343            name (string): Name of group.
344            user_name (string): User of interest.
345
346        Returns:
347            (bool): False if user not a member.
348        """
349        self.project_service.set_auth(self._token_project)
350        return self.project_service.get_is_group_member(grp_name, user)
351
352    def list_group_maintainers(self, name):
353        """
354        Get the maintainers of a group.
355
356        Args:
357            name (string): Name of group to query.
358
359        Returns:
360            (list[string]): List of maintainer names.
361
362        Raises:
363            requests.HTTPError on failure.
364        """
365        self.project_service.set_auth(self._token_project)
366        return self.project_service.list_group_maintainers(name)
367
368    def add_group_maintainer(self, name, user):
369        """
370        Add the given user to the named group.
371
372        Both group and user must already exist for this to succeed.
373
374        Args:
375            name (string): Name of group.
376            user (string): User to add to group.
377
378        Raises:
379            requests.HTTPError on failure.
380        """
381        self.project_service.set_auth(self._token_project)
382        self.project_service.add_group_maintainer(name, user)
383
384    def delete_group_maintainer(self, grp_name, user):
385        """
386        Delete the given user to the named group.
387
388        Both group and user must already exist for this to succeed.
389
390        Args:
391            name (string): Name of group.
392            user (string): User to add to group.
393
394        Raises:
395            requests.HTTPError on failure.
396        """
397        self.project_service.set_auth(self._token_project)
398        self.project_service.delete_group_maintainer(grp_name, user)
399
400    def get_is_group_maintainer(self, grp_name, user):
401        """
402        Check if the given user is a member of the named group.
403
404        Args:
405            name (string): Name of group.
406            user (string): User of interest.
407
408        Returns:
409            (bool): False if user not a member.
410        """
411        self.project_service.set_auth(self._token_project)
412        return self.project_service.get_is_group_maintainer(grp_name, user)
413
414    def list_permissions(self, group_name=None, resource=None):
415        """
416        List permission sets associated filtering by group and/or resource.
417
418        Args:
419            group_name (string): Name of group.
420            resource (intern.resource.boss.Resource): Identifies which data
421                model object to operate on.
422
423        Returns:
424            (list): List of permissions.
425
426        Raises:
427            requests.HTTPError on failure.
428        """
429        self.project_service.set_auth(self._token_project)
430        return self.project_service.list_permissions(group_name, resource)
431
432    def get_permissions(self, grp_name, resource):
433        """
434        Get permissions associated the group has with the given resource.
435
436        Args:
437            grp_name (string): Name of group.
438            resource (intern.resource.boss.Resource): Identifies which data
439                model object to operate on.
440
441        Returns:
442            (list): List of permissions.
443
444        Raises:
445            requests.HTTPError on failure.
446        """
447        self.project_service.set_auth(self._token_project)
448        return self.project_service.get_permissions(grp_name, resource)
449
450    def add_permissions(self, grp_name, resource, permissions):
451        """
452        Add additional permissions for the group associated with the resource.
453
454        Args:
455            grp_name (string): Name of group.
456            resource (intern.resource.boss.Resource): Identifies which data
457                model object to operate on.
458            permissions (list): List of permissions to add to the given resource
459
460        Raises:
461            requests.HTTPError on failure.
462        """
463        self.project_service.set_auth(self._token_project)
464        self.project_service.add_permissions(grp_name, resource, permissions)
465
466    def update_permissions(self, grp_name, resource, permissions):
467        """
468        Update permissions for the group associated with the given resource.
469
470        Args:
471            grp_name (string): Name of group.
472            resource (intern.resource.boss.Resource): Identifies which data
473                model object to operate on
474            permissions (list): List of permissions to add to the given resource
475
476        Raises:
477            requests.HTTPError on failure.
478        """
479        self.project_service.set_auth(self._token_project)
480        self.project_service.update_permissions(grp_name, resource, permissions)
481
482    def delete_permissions(self, grp_name, resource):
483        """
484        Removes permissions from the group for the given resource.
485
486        Args:
487            grp_name (string): Name of group.
488            resource (intern.resource.boss.Resource): Identifies which data
489                model object to operate on.
490
491        Raises:
492            requests.HTTPError on failure.
493        """
494        self.project_service.set_auth(self._token_project)
495        self.project_service.delete_permissions(grp_name, resource)
496
497    def get_user_roles(self, user):
498        """
499        Get roles associated with the given user.
500
501        Args:
502            user (string): User name.
503
504        Returns:
505            (list): List of roles that user has.
506
507        Raises:
508            requests.HTTPError on failure.
509        """
510        self.project_service.set_auth(self._token_project)
511        return self.project_service.get_user_roles(user)
512
513    def add_user_role(self, user, role):
514        """
515        Add role to given user.
516
517        Args:
518            user (string): User name.
519            role (string): Role to assign.
520
521        Raises:
522            requests.HTTPError on failure.
523        """
524        self.project_service.set_auth(self._token_project)
525        self.project_service.add_user_role(user, role)
526
527    def delete_user_role(self, user, role):
528        """
529        Remove role from given user.
530
531        Args:
532            user (string): User name.
533            role (string): Role to remove.
534
535        Raises:
536            requests.HTTPError on failure.
537        """
538        self.project_service.set_auth(self._token_project)
539        self.project_service.delete_user_role(user, role)
540
541    def get_user(self, user):
542        """
543        Get user's data (first and last name, email, etc).
544
545        Args:
546            user (string): User name.
547
548        Returns:
549            (dictionary): User's data encoded in a dictionary.
550
551        Raises:
552            requests.HTTPError on failure.
553        """
554        self.project_service.set_auth(self._token_project)
555        return self.project_service.get_user(user)
556
557    def get_user_groups(self, user):
558        """
559        Get user's group memberships.
560
561        Args:
562            user (string): User name.
563
564        Returns:
565            (list): User's groups.
566
567        Raises:
568            requests.HTTPError on failure.
569        """
570        self.project_service.set_auth(self._token_project)
571        return self.project_service.get_user_groups(user)
572
573    def add_user(
574            self, user,
575            first_name=None, last_name=None,
576            email=None, password=None
577        ):
578        """
579        Add a new user.
580
581        Args:
582            user (string): User name.
583            first_name (optional[string]): User's first name.  Defaults to None.
584            last_name (optional[string]): User's last name.  Defaults to None.
585            email: (optional[string]): User's email address.  Defaults to None.
586            password: (optional[string]): User's password.  Defaults to None.
587
588        Raises:
589            requests.HTTPError on failure.
590        """
591        self.project_service.set_auth(self._token_project)
592        self.project_service.add_user(
593            user, first_name, last_name, email, password)
594
595    def delete_user(self, user):
596        """
597        Delete the given user.
598
599        Args:
600            user (string): User name.
601
602        Raises:
603            requests.HTTPError on failure.
604        """
605        self.project_service.set_auth(self._token_project)
606        self.project_service.delete_user(user)
607
608    def _list_resource(self, resource):
609        """
610        List all instances of the given resource type.
611
612        Use the specific list_<resource>() methods instead:
613            list_collections()
614            list_experiments()
615            list_channels()
616            list_coordinate_frames()
617
618        Args:
619            resource (intern.resource.boss.BossResource): resource.name may be
620                an empty string.
621
622        Returns:
623            (list)
624
625        Raises:
626            requests.HTTPError on failure.
627        """
628        self.project_service.set_auth(self._token_project)
629        return super(BossRemote, self).list_project(resource=resource)
630
631    def list_collections(self):
632        """
633        List all collections.
634
635        Returns:
636            (list)
637
638        Raises:
639            requests.HTTPError on failure.
640        """
641        coll = CollectionResource(name='')
642        return self._list_resource(coll)
643
644    def list_experiments(self, collection_name):
645        """
646        List all experiments that belong to a collection.
647
648        Args:
649            collection_name (string): Name of the parent collection.
650
651        Returns:
652            (list)
653
654        Raises:
655            requests.HTTPError on failure.
656        """
657        exp = ExperimentResource(
658            name='', collection_name=collection_name, coord_frame='foo')
659        return self._list_resource(exp)
660
661    def list_channels(self, collection_name, experiment_name):
662        """
663        List all channels belonging to the named experiment that is part
664        of the named collection.
665
666        Args:
667            collection_name (string): Name of the parent collection.
668            experiment_name (string): Name of the parent experiment.
669
670        Returns:
671            (list)
672
673        Raises:
674            requests.HTTPError on failure.
675        """
676        dont_care = 'image'
677        chan = ChannelResource(
678            name='', collection_name=collection_name,
679            experiment_name=experiment_name, type=dont_care)
680        return self._list_resource(chan)
681
682    def list_coordinate_frames(self):
683        """
684        List all coordinate_frames.
685
686        Returns:
687            (list)
688
689        Raises:
690            requests.HTTPError on failure.
691        """
692        cf = CoordinateFrameResource(name='')
693        return self._list_resource(cf)
694
695    def get_channel(self, chan_name, coll_name, exp_name):
696        """
697        Helper that gets a fully initialized ChannelResource for an *existing* channel.
698
699        Args:
700            chan_name (str): Name of channel.
701            coll_name (str): Name of channel's collection.
702            exp_name (str): Name of channel's experiment.
703
704        Returns:
705            (intern.resource.boss.ChannelResource)
706        """
707        chan = ChannelResource(chan_name, coll_name, exp_name)
708        return self.get_project(chan)
709
710    def create_project(self, resource):
711        """
712        Create the entity described by the given resource.
713
714        Args:
715            resource (intern.resource.boss.BossResource)
716
717        Returns:
718            (intern.resource.boss.BossResource): Returns resource of type
719                requested on success.
720
721        Raises:
722            requests.HTTPError on failure.
723        """
724        self.project_service.set_auth(self._token_project)
725        return self.project_service.create(resource)
726
727    def get_project(self, resource):
728        """
729        Get attributes of the data model object named by the given resource.
730
731        Args:
732            resource (intern.resource.boss.BossResource): resource.name as well
733                as any parents must be identified to succeed.
734
735        Returns:
736            (intern.resource.boss.BossResource): Returns resource of type
737                requested on success.
738
739        Raises:
740            requests.HTTPError on failure.
741        """
742        self.project_service.set_auth(self._token_project)
743        return self.project_service.get(resource)
744
745    def update_project(self, resource_name, resource):
746        """
747        Updates an entity in the data model using the given resource.
748
749        Args:
750            resource_name (string): Current name of the resource (in case the
751                resource is getting its name changed).
752            resource (intern.resource.boss.BossResource): New attributes for
753                the resource.
754
755        Returns:
756            (intern.resource.boss.BossResource): Returns updated resource of
757                given type on success.
758
759        Raises:
760            requests.HTTPError on failure.
761        """
762        self.project_service.set_auth(self._token_project)
763        return self.project_service.update(resource_name, resource)
764
765    def delete_project(self, resource):
766        """
767        Deletes the entity described by the given resource.
768
769        Args:
770            resource (intern.resource.boss.BossResource)
771
772        Raises:
773            requests.HTTPError on a failure.
774        """
775        self.project_service.set_auth(self._token_project)
776        self.project_service.delete(resource)
777
778    def list_metadata(self, resource):
779        """
780        List all keys associated with the given resource.
781
782        Args:
783            resource (intern.resource.boss.BossResource)
784
785        Returns:
786            (list)
787
788        Raises:
789            requests.HTTPError on a failure.
790        """
791        self.metadata_service.set_auth(self._token_metadata)
792        return self.metadata_service.list(resource)
793
794    def create_metadata(self, resource, keys_vals):
795        """
796        Associates new key-value pairs with the given resource.
797
798        Will attempt to add all key-value pairs even if some fail.
799
800        Args:
801            resource (intern.resource.boss.BossResource)
802            keys_vals (dictionary): Collection of key-value pairs to assign to
803                given resource.
804
805        Raises:
806            HTTPErrorList on failure.
807        """
808        self.metadata_service.set_auth(self._token_metadata)
809        self.metadata_service.create(resource, keys_vals)
810
811    def get_metadata(self, resource, keys):
812        """
813        Gets the values for given keys associated with the given resource.
814
815        Args:
816            resource (intern.resource.boss.BossResource)
817            keys (list)
818
819        Returns:
820            (dictionary)
821
822        Raises:
823            HTTPErrorList on failure.
824        """
825        self.metadata_service.set_auth(self._token_metadata)
826        return self.metadata_service.get(resource, keys)
827
828    def update_metadata(self, resource, keys_vals):
829        """
830        Updates key-value pairs with the given resource.
831
832        Will attempt to update all key-value pairs even if some fail.
833        Keys must already exist.
834
835        Args:
836            resource (intern.resource.boss.BossResource)
837            keys_vals (dictionary): Collection of key-value pairs to update on
838                the given resource.
839
840        Raises:
841            HTTPErrorList on failure.
842        """
843        self.metadata_service.set_auth(self._token_metadata)
844        self.metadata_service.update(resource, keys_vals)
845
846    def delete_metadata(self, resource, keys):
847        """
848        Deletes the given key-value pairs associated with the given resource.
849
850        Will attempt to delete all key-value pairs even if some fail.
851
852        Args:
853            resource (intern.resource.boss.BossResource)
854            keys (list)
855
856        Raises:
857            HTTPErrorList on failure.
858        """
859        self.metadata_service.set_auth(self._token_metadata)
860        self.metadata_service.delete(resource, keys)
861
862    def parse_bossURI(self, uri): # type: (str) -> Resource
863        """
864        Parse a bossDB URI and handle malform errors.
865
866        Arguments:
867            uri (str): URI of the form bossdb://<collection>/<experiment>/<channel>
868
869        Returns:
870            Resource
871
872        """
873        t = uri.split("://")[1].split("/")
874        if len(t) == 3:
875            return self.get_channel(t[2], t[0], t[1])
876        raise ValueError("Cannot parse URI " + uri + ".")
877
878    def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], no_cache=None, access_mode=CacheMode.no_cache, parallel: bool = True, **kwargs):
879            """Get a cutout from the volume service.
880
881            Note that access_mode=no_cache is desirable when reading large amounts of
882            data at once.  In these cases, the data is not first read into the
883            cache, but instead, is sent directly from the data store to the
884            requester.
885
886            Args:
887                resource (intern.resource.boss.resource.ChannelResource | str): Channel or layer Resource. If a
888                    string is provided instead, BossRemote.parse_bossURI is called instead on a URI-formatted
889                    string of the form `bossdb://collection/experiment/channel`.
890                resolution (int): 0 indicates native resolution.
891                x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
892                y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
893                z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
894                time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
895                id_list (optional [list[int]]): list of object ids to filter the cutout by.
896                no_cache (optional [boolean or None]): Deprecated way to specify the use of cache to be True or False.
897                    access_mode should be used instead
898                access_mode (optional [Enum]): Identifies one of three cache access options:
899                    cache = Will check both cache and for dirty keys
900                    no_cache = Will skip cache check but check for dirty keys
901                    raw = Will skip both the cache and dirty keys check
902                parallel (bool: True): Whether downloads should be parallelized using multiprocessing
903
904                TODO: Add mode to documentation
905
906
907            Returns:
908                (numpy.array): A 3D or 4D (time) numpy matrix in (time)ZYX order.
909
910            Raises:
911                requests.HTTPError on error.
912            """
913            if no_cache is not None:
914                warnings.warn("The no-cache option has been deprecated and will not be used in future versions of intern.")
915                warnings.warn("Please from intern.service.boss.volume import CacheMode and use access_mode=CacheMode.[cache,no-cache,raw] instead.")
916            if no_cache and access_mode != CacheMode.no_cache:
917                warnings.warn("Both no_cache and access_mode were used, please use access_mode only. As no_cache has been deprecated. ")
918                warnings.warn("Your request will be made using the default mode no_cache.")
919                access_mode=CacheMode.no_cache
920            if no_cache:
921                access_mode=CacheMode.no_cache
922            elif no_cache == False:
923                access_mode=CacheMode.cache
924            return self._volume.get_cutout(
925                resource, resolution,
926                x_range, y_range, z_range, time_range,
927                id_list, access_mode,
928                parallel=parallel, **kwargs
929            )
930    
931    def create_cutout_to_black(self, resource, resolution, x_range, y_range, z_range, time_range=None):
932        """Post a black cutout to the volume service.
933
934        Args:
935            resource (intern.resource.Resource): Resource compatible with cutout operations.
936            resolution (int): 0 indicates native resolution.
937            x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
938            y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
939            z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
940            time_range (optional [list[int]]): time range such as [30, 40] which means t>=30 and t<40.
941
942        Returns:
943            (): Return type depends on volume service's implementation.
944
945        Raises:
946            RuntimeError when given invalid resource.
947            Other exceptions may be raised depending on the volume service's implementation.
948        """
949        if not resource.valid_volume():
950            raise RuntimeError('Resource incompatible with the volume service.')
951        return self._volume.create_cutout_to_black(
952            resource, resolution, x_range, y_range, z_range, time_range)
953        
954    def get_experiment(self, coll_name, exp_name):
955        """
956        Convenience method that gets experiment resource.
957
958        Args:
959            coll_name (str): Collection name
960            exp_name (str): Experiment name
961
962        Returns:
963            (ExperimentResource)
964        """
965        exp = ExperimentResource(exp_name, coll_name)
966        return self.get_project(exp)
967
968    def get_coordinate_frame(self, name):
969        """
970        Convenience method that gets coordinate frame resource
971
972        Args:
973            name (str): Name of the coordinate frame
974
975        Returns:
976            (CoordinateFrameResource)
977        """
978        cf = CoordinateFrameResource(name)
979        return self.get_project(cf)
980
981    def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs):
982            """
983            Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step.
984
985            Args:
986                resource (intern.resource.Resource): Resource compatible with cutout operations.
987                resolution (int): 0 indicates native resolution.
988                x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20.
989                y_range (list[int]): y range such as [10, 20] which means y>=10 and y<20.
990                z_range (list[int]): z range such as [10, 20] which means z>=10 and z<20.
991
992            Returns:
993                (string): Return neuroglancer link.
994
995            Raises:
996                RuntimeError when given invalid resource.
997                Other exceptions may be raised depending on the volume service's implementation.
998            """
999            return self._volume.get_neuroglancer_link(resource, resolution, x_range, y_range, z_range, **kwargs)
1000
1001    def get_extents(self, resource):
1002            """Get extents of the reource
1003
1004            Args:
1005                resource (intern.resource.boss.BossResource.ExperimentResource)
1006
1007            Returns:
1008                extents (array): [[x-min, max-x], [y-min, max-y], [z-min, max-z]]
1009
1010            Raises:
1011                requests.HTTPError on failure.
1012            """
1013            coord_frame = self.get_coordinate_frame(resource.coord_frame)
1014            min_point = [coord_frame.x_start, coord_frame.y_start, coord_frame.z_start]
1015            max_point = [coord_frame.x_stop, coord_frame.y_stop, coord_frame.z_stop]
1016            extents = [[min_point[0],max_point[0]],[min_point[1],max_point[1]],[min_point[2],max_point[2]]]
1017
1018            return extents
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)