def test_sound_details_non_existent(client): """ Requesting the sound details of a non-existent sound should result in a not-found error response. """ response = client.get('/sounds/1/') assert status(response) == 'not_found'
def test_create_sound_not_authenticated(client): """ Get a no existent sound in an empty database should result in 301 error. Any client can make this request (no authentication needed). """ response = client.post('/sounds/', json={}) assert status(response) == 'forbidden'
def test_an_admin_view(admin_client): """ An admin client should be able to access the admin interface, just as expected. """ response = admin_client.get('/admin/') assert status(response) == 'ok'
def decorated_function(*args, **kwargs): signature = hmac.new(secret.api_key, msg=request.get_data(), digestmod='sha1').hexdigest() if request.headers.get('X-Hub-Signature') != 'sha1=' + signature: return status(401) return f(*args, **kwargs)
def test_an_admin_view_anonymous(client): """ An anonymous client should not be able to access the admin interface. The server responds with a redirection to the login page. """ response = client.get('/admin/') assert status(response) == 'found' assert response.url.startswith('/admin/login/')
def test_create_sound_autenticated(logged_in_client): """ Logged-in users should be able to upload new sounds if the data provided is complete. """ response = logged_in_client.post('/sounds/', data=sound_upload('a.ogg')) assert status(response) == 'created' assert is_subdict(sound_details('a.ogg'), decode(response))
def test_list_sounds_empty_database(client): """ Listing sounds from an empty database should result in an empty list. Any client can make this request (no authentication needed). """ response = client.get('/sounds/') assert status(response) == 'ok' assert decode(response) == []
def test_sound_details(client, logged_in_client): """ Any user can request details about an uploaded sound. These details should contain complete information about the sound description and properties. """ # Upload a sound while authenticated response = logged_in_client.post('/sounds/', data=sound_upload('a.ogg')) # Request details while not authenticated response = client.get('/sounds/1/') assert status(response) == 'ok' assert is_subdict(sound_details('a.ogg'), decode(response))
def test_create_sound_autenticated_bad_request(logged_in_client, data): """ When posting a new sound, if the information provided is incomplete, the server should response with a bad request status error. """ # Make sure we never send an empty file... (otherwise the bad-request # response error could be caused by an empty file and could be hiding # the expected behavior) if 'sound' in data: data['sound'].seek(0) response = logged_in_client.post('/sounds/', data=data) assert status(response) == 'bad_request'
def test_list_sounds_filled_database(client, logged_in_client): """ Listing sounds from a filled database should result in a non-empty list. Any client can make this request (no authentication needed). """ # Upload a sound while authenticated logged_in_client.post('/sounds/', data=sound_upload('a.ogg')) logged_in_client.post('/sounds/', data=sound_upload('b.ogg')) # Request details while not authenticated response = client.get('/sounds/') assert status(response) == 'ok' response = decode(response) assert len(response) == 2 assert is_subdict(sound_details('a.ogg'), response[0]) assert is_subdict(sound_details('b.ogg'), response[1])
def download(self, options): """ Start the download process, meta manager. Grab the folder list from DA, and process each folder """ self.session = common.setup_requests(self.session, WEBSITE_NAME) if options.username: # # Use login information, if provided. # self.login(options) status = common.status() status = self.download_gallery(options.url_to_fetch, options.download_folder, options, status, root=True) return status.return_counts()
def push(): if not request.is_json: return status(400) data = request.json if not ('ref' in data and data['ref'].startswith('refs/tags/')): return status(200) base = data['compare_url'] + 'api/v1' headers = { 'Accept': 'application/json', 'Authorization': 'token ' + secret.token.gitea, } repo = data['repository'] # get tag information uri = uritemplate.expand(base + '/repos/{owner}/{repo}/git/tags/{sha}', owner=repo['owner']['username'], repo=repo['name'], sha=data['after']) r = requests.get(uri, headers=headers) if r.status_code != 200: return status(500, message=f'error fetching "{uri}"') tag = r.json() # create release uri = uritemplate.expand(base + '/repos/{owner}/{repo}/releases', owner=repo['owner']['username'], repo=repo['name']) payload = { 'body': tag['message'], 'draft': False, 'name': kebab2normal(repo['name']) + ' ' + tag['tag'], 'prerelease': False, 'tag_name': tag['tag'], 'target_commitish': repo['default_branch'], } r = requests.post(uri, headers=headers, json=payload) if r.status_code != 201: return status(500, message=f'error fetching "{uri}"') release = r.json() # create release zip with SpooledTemporaryFile() as f: with TemporaryDirectory() as d: p = run(['git', 'clone', repo['clone_url'], d]) if p.returncode != 0: return status(500, message='error cloning repository') cmd = ['sh', os.path.join(d, '.bin', 'release.sh'), tag['tag']] if not os.path.exists(cmd[1]): cmd = ['git', 'archive', '--format=zip', tag['tag']] p = run(cmd, stdout=PIPE, cwd=d) if p.returncode != 0: return status(500, message='error creating archive') b = p.stdout # upload release zip uri = uritemplate.expand(base + '/repos/{owner}/{repo}/releases/{id}/assets?name={name}', owner=repo['owner']['username'], repo=repo['name'], id=release['id'], name=repo['name'] + '.zip') payload = { 'attachment': (repo['name'] + '.zip', b, 'application/zip'), } r = requests.post(uri, headers=headers, files=payload) if r.status_code != 201: return status(500, message='error uploading archive') return status(200, message='release created')
def status(): return common.status()
import requests import time import common import const while True: cmd = requests.get("http://%s/get_command" % const.remote_server).text print "Got command %s" % cmd if cmd == "on": common.on() if cmd == "off": common.off() status = common.status() print "Sending status %s" % status requests.post("http://%s/update_status" % const.remote_server, data={"status": status}) time.sleep(5)
def download(self, options): """ # As of 4/24/2014 # # Examples of # """ print "AC Paradise" if options.startingplace != 0: counter = options.startingplace else: counter = 1 status = common.status() while True: cosplay_index_links = self.download_acp_cosplayer_index(\ url=website_cosplayer_index % (options.url_to_fetch, counter), timeout=45) if len(cosplay_index_links) == 0: # # No download links, stop processing, and return totals # # return (total_downloaded, total_skipped) return status.return_counts() else: for x in cosplay_index_links: (costume_name, display_page_number) =\ self.extract_ci_details(x) costume_name = common.clean_filename(costume_name) print "\nCostume name : %s - %s" % (costume_name, website_base_url%\ display_page_number) costume_webpage = common.fetch_webpage(\ session=self.session, url=website_base_url % display_page_number, timeout=45) costume_soup = BeautifulSoup(costume_webpage) costume_links = costume_soup.find_all("img") for y in costume_links: if str(y).find(website_photo_base) != -1: # # Remove thumbnail # file_to_download = y["src"].replace("-t", "") file_to_download = file_to_download.strip() file_to_download = common.clean_filename(\ file_to_download, max_length=240) # # Does directory exist? If not create it # if not os.path.exists(\ options.download_folder + costume_name): os.makedirs(options.download_folder + \ costume_name + os.sep) # # Check for file already existing, # if so, don't download # if os.path.exists(\ options.download_folder + costume_name + os.sep + os.path.split(file_to_download)[1]): status.add_skipped(file_to_download, options) else: # # Download file # if common.download_file(\ session=self.session, url=file_to_download, filename=os.path.split(file_to_download)[1], download_folder=options.download_folder + costume_name + os.sep, timeout=45): status.add_download(file_to_download, options) else: status.add_error(file_to_download, options) counter += 1 # # Increment page count # return status.return_counts()
def push(): if not request.is_json: return status(400) data = request.json if not ('created' in data and data['created'] and \ 'ref' in data and data['ref'].startswith('refs/tags/')): return status(200) headers = { 'Accept': 'application/vnd.github.v3+json', 'Authorization': 'token ' + secret.token.github, } uri = uritemplate.expand( data['repository']['git_refs_url']) + '/' + data['ref'].split('/', 1)[1] r = requests.get(uri, headers=headers) if r.status_code != 200: return status(500, message=f'error fetching "{uri}"') try: uri = r.json()['object']['url'] except ValueError: return status(500, message='error parsing JSON') r = requests.get(uri, headers=headers) if r.status_code != 200: return status(500, message=f'error fetching "{uri}"') try: tag = r.json() except ValueError: return status(500, message='error parsing JSON') message = tag['message'].strip() tag = tag['tag'] uri = uritemplate.expand(data['repository']['releases_url']) name = data['repository']['name'] payload = { 'tag_name': tag, 'target_commitish': data['repository']['default_branch'], 'name': kebab2normal(name) + ' ' + tag, 'body': message, 'draft': False, 'prerelease': False, } r = requests.post(uri, json=payload, headers=headers) if r.status_code == 422 and r.json( )['errors'][0]['code'] == 'already_exists': uri += '/tags/' + tag r = requests.get(uri, headers=headers) if r.status_code not in [200, 201]: return status(500, message=f'error fetching "{uri}"') try: release = r.json() except ValueError: return status(500, message='error parsing JSON') with SpooledTemporaryFile() as f: with TemporaryDirectory() as d: p = run(['git', 'clone', data['repository']['clone_url'], d]) if p.returncode != 0: return status(500, message='error cloning repository') cmd = ['sh', os.path.join(d, '.bin', 'release.sh'), tag] if not os.path.exists(cmd[1]): cmd = ['git', 'archive', '--format=zip', tag] p = run(cmd, stdout=PIPE, cwd=d) if p.returncode != 0: return status(500, message='error creating archive') b = p.stdout headers.update({ 'Content-Length': str(len(b)), 'Content-Type': 'application/zip', }) uri = uritemplate.expand(release['upload_url'], name=(name + '.zip')) r = requests.post(uri, data=b, headers=headers) if r.status_code != 201: return status(500, message='error uploading archive') return status(200, message='release created')
def status(): return jsonify(**{"humidity": common.status(), "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")})