def send_user_email(dbo, sendinguser, user, subject, body): """ Sends an email to users. sendinguser: The username of the person sending the email (we will look up their email) user: can be an individual username, a rolename or the translated version of (all) or (everyone) to denote all users. """ DEFAULT_EMAIL = "*****@*****.**" sendinguser = users.get_users(dbo, sendinguser) if len(sendinguser) == 0: fromadd = DEFAULT_EMAIL else: fromadd = sendinguser[0]["EMAILADDRESS"] if fromadd is None or fromadd.strip() == "": fromadd = DEFAULT_EMAIL al.debug("from: %s (%s), to: %s" % (sendinguser, fromadd, user), "utils.send_user_email", dbo) allusers = users.get_users(dbo) for u in allusers: # skip if we have no email address - we can't send it. if u["EMAILADDRESS"] is None or u["EMAILADDRESS"].strip() == "": continue if user == "*": send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body) elif u["USERNAME"] == user: send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body) elif nulltostr(u["ROLES"]).find(user) != -1: send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body)
def send_user_email(dbo, sendinguser, user, subject, body): """ Sends an email to users. sendinguser: The username of the person sending the email (we will look up their email) user: can be an individual username, a rolename or the translated version of (all) or (everyone) to denote all users. """ l = dbo.locale DEFAULT_EMAIL = "*****@*****.**" sendinguser = users.get_users(dbo, sendinguser) if len(sendinguser) == 0: fromadd = DEFAULT_EMAIL else: fromadd = sendinguser[0]["EMAILADDRESS"] if fromadd is None or fromadd.strip() == "": fromadd = DEFAULT_EMAIL allusers = users.get_users(dbo) for u in allusers: # skip if we have no email address - we can't send it. if u["EMAILADDRESS"] is None or u["EMAILADDRESS"].strip() == "": continue if user == _("(all)", l) or user == _("(everyone)", l): send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body) elif u["USERNAME"] == user: send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body) elif nulltostr(u["ROLES"]).find(user) != -1: send_email(dbo, fromadd, u["EMAILADDRESS"], "", subject, body)
def test_request_response_with_decorator(self, mock_get): """Mocking using a decorator""" mock_get.return_value.status_code = 200 # Mock status code of response. response = get_users() # Assert that the request-response cycle completed successfully. self.assertEqual(response.status_code, 200)
def test_request_response_with_decorator(self, mock_get): mockuser = [{ 'phone': '514-794-6957', 'first_name': 'Brant', 'last_name': 'Mekhi', 'id': 0 }, { 'phone': '772-370-0117', 'first_name': 'Thalia', 'last_name': 'Kenyatta', 'id': 1 }, { 'phone': '176-290-7637', 'first_name': 'Destin', 'last_name': 'Soledad', 'id': 2 }] # Mock status code of response. mock_get.return_value.status_code = 200 mock_get.return_value.json.return_value = mockuser response = get_users() # filter to find user 2 user = get_user(2) # Assert that the request-response cycle completed successfully. self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), mockuser) self.assertEqual(user, mockuser[2])
def main(size: int = 10**4) -> None: users = get_users(add_naive=False) timings = [] for test in tests: print("Testing:", test.long_name) temp_time = [] timings.append(temp_time) for user in users: test_instance = test(size, user.tree) # type: AbstractTest print("\t" + user.class_name, end=": ") try: tested_time = test_instance.time_it() temp_time.append(tested_time) except (RecursionError, AttributeError, AssertionError, KeyError): temp_time.append(0) print(temp_time[-1]) pyplot.figure(figsize=(20, 10)) pyplot.legend(handles=[ patches.Patch(color=user.color_code, label=user.class_name) for user in users ]) for j in range(len(tests)): for i in range(len(users)): pyplot.plot([j], [timings[j][i]], "o", color=users[i].color_code) pyplot.xticks(range(len(tests)), [test.short_name.replace(" ", "\n") for test in tests]) pyplot.title("Prikaz Ĩasov za N=" + str(size)) pyplot.savefig("plot.png") pyplot.show()
def test_mock_whole_function(self): """Mocking a whole function """ mock_get_patcher = patch('users.requests.get') users = [{ "id": 0, "first_name": "Adrian", "last_name": "Francis", "phone": "254 727 440 297" }] # start patching 'requests.get' mock_get = mock_get_patcher.start() #configure the mock to return a response with a status of 200 and a list of all users mock_get.return_value = Mock(status_code=200) mock_get.return_value.json.return_value = users #call the service that will send a request to the server response = get_users() # stop patching 'requests' mock_get_patcher.stop() # assert that the request-reponse cycle completed successfully self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), users)
def get_web(): from buildbot.status import html from buildbot.status.web import authz, auth import users users = users.get_users() authz_cfg = authz.Authz(auth=auth.BasicAuth(users), view=True, forceBuild='auth', forceAllBuilds='auth', pingBuilder='auth', gracefulShutdown=False, pauseSlave='auth', stopBuild='auth', stopAllBuilds='auth', cancelPendingBuild='auth', cancelAllPendingBuilds='auth', stopChange='auth', cleanShutdown=False, showUsersPage='auth') return html.WebStatus(http_port="tcp:8010:interface=127.0.0.1", authz=authz_cfg, change_hook_dialects={ 'base': True, 'github': {} }, change_hook_auth=['file:changehook.passwd'])
def test_mock_whole_function(self): """Mocking a whole function""" mock_get_patcher = patch('users.requests.get') users = [{ "id": 0, "first_name": "Oleg", "last_name": "Mikheenko", "phone": "999-333-1111" }] # Start patching 'requests.get'. mock_get = mock_get_patcher.start() # Configure the mock to return a response with status code 200 and a list of users. mock_get.return_value = Mock(status_code=200) mock_get.return_value.json.return_value = users # Call the service, which will send a request to the server. response = get_users() # Stop patching 'requests'. mock_get_patcher.stop() # Assert that the request-response cycle completed successfully. self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), users)
def invite(id): board_users = boards.get_secret_board_users(id) board = boards.get_board(id) userlist = users.get_users() if users.user_role() != 2: return redirect(url_for('error')) if request.method == "GET": return render_template("invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist) if request.method == "POST": user_id = request.form["users"] if session["csrf_token"] != request.form["csrf_token"]: abort(403) if int(user_id) == 0: return render_template("invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist, errormessage="Valitse kƤyttƤjƤ!") # Tarkastetaan, onko kƤyttƤjƤ jo alueella user_invited = False for row in board_users: for elem in row: if int(user_id) == elem: user_invited = True if request.form["submit"] == 'remove': if not user_invited: return render_template( "invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist, errormessage="KƤyttƤjƤ ei ole alueella!") if boards.remove_user(user_id, id): board_users = boards.get_secret_board_users(id) return render_template("invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist) elif request.form["submit"] == 'add': if user_invited: return render_template("invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist, errormessage="KƤyttƤjƤ on jo lisƤtty!") if boards.invite_user(user_id, id): board_users = boards.get_secret_board_users(id) return render_template("invite.html", id=id, boardname=board[0], board_users=board_users, userlist=userlist)
def all_users(): user_id = session["user_id"] if users.is_admin(user_id): all_users = users.get_users() return render_template("/all_users.html", users=all_users) else: abort(403)
def get_web(): from buildbot.status import html from buildbot.status.web import authz, auth import users users = users.get_users() authz_cfg = authz.Authz( auth = auth.BasicAuth(users), view = True, forceBuild = 'auth', forceAllBuilds = 'auth', pingBuilder = 'auth', gracefulShutdown = False, pauseSlave = 'auth', stopBuild = 'auth', stopAllBuilds = 'auth', cancelPendingBuild = 'auth', cancelAllPendingBuilds = 'auth', stopChange = 'auth', cleanShutdown = False, showUsersPage = 'auth' ) return html.WebStatus( http_port = "tcp:8010:interface=127.0.0.1", authz = authz_cfg, change_hook_dialects = {'github' : {}}, change_hook_auth = ['file:changehook.passwd'] )
def test_get_users(self): users.add_user('kevin', 1, 'password') users.add_user('Mike', 2, 'password') userlist = users.get_users() self.assertEquals(len(userlist), 2) unames = ['kevin', 'Mike'] for u in userlist: self.assertIn(u.uname, unames)
def main(): """Main app to execute subscription based email notifications.""" users_json = users.get_users() # At start of subscription, drop all content and populate db without sending email posts.drop_contents() for _ in posts.get(users_json): pass while True: # Sleep for a day (-80 seconds) to fetch posts print("sleeping...") time.sleep(86320) # Get users' json file for every iteration - allows for updates during operation users_json = users.get_users() user_posts = zip(users_json, posts.get(users_json)) for user, post in user_posts: mail.write_email(user, post)
def test_print_company_names_ending_with_group(self): # write response to a binary file with open('./users.json', mode='wb') as json_filename: json_filename.write(get_users().content) json_filename.close() extract_company_names('./users.json')
def test_request_response_with_context_manager(self): """Mocking using a context manager""" with patch('users.requests.get') as mock_get: # Configure the mock to return a response with status code 200. mock_get.return_value.status_code = 200 # Call the function, which will send a request to the server. response = get_users() self.assertEqual(response.status_code, 200)
def test_request_response_with_context_manager(self): """Mocking using a context manager""" with patch('users.requests.get') as mock_get: #configure the mock to return a response with a status of 200 mock_get.return_value.status_code = 200 #call the function, which will send a request to the server response = get_users() # assert that the request-response cycle completed successfully with status code 200 self.assertEqual(response.status_code, 200)
def view_leaderboard(): if 'user' in session: user_id = session['user']['id'] tag_count, verify_count = get_tag_count(user_id) return render_template("leaderboard.html", users=get_users(), username=session['user']['name'], tag_count=tag_count, verify_count=verify_count) else: return redirect(url_for('bp.login'))
def admin_list_users(): """admin function to list users""" usr = verify_user() if not usr or not users.is_admin(usr["email"]): raise EXCEPTION_UNAUTHORIZED return [{ "name": usr["name"], "email": usr["email"] } for usr in users.get_users()]
def getUsers(): if request.method == "GET": return users.get_users() elif request.method=="POST": return users.post_user() elif request.method=="PATCH": return users.patch_user() elif request.method=="DELETE": return users.delete_user() else : Response("not supported", mimetype="text/html", status=500)
def email_uncompleted_upto_today(dbo): """ Goes through all system users and emails them their diary for the day - unless the option is turned off. """ if not configuration.email_diary_notes(dbo): return l = dbo.locale try: allusers = users.get_users(dbo) except Exception,err: al.error("failed getting list of users: %s" % str(err), "diary.email_uncompleted_upto_today", dbo)
def email_uncompleted_upto_today(dbo): """ Goes through all system users and emails them their diary for the day - unless the option is turned off. """ if not configuration.email_diary_notes(dbo): return l = dbo.locale try: allusers = users.get_users(dbo) except Exception, err: al.error("failed getting list of users: %s" % str(err), "diary.email_uncompleted_upto_today", dbo)
def main() -> None: mins = 0 while True: notify_users = users.get_users() for user in notify_users: try: keep_alive(user) if mins == 0: notify(user) except SessionError: handle_session_error(user["_id"], user["email"]) except SkywardError: wait_for(30) mins = (mins + 1) % 10 wait_for(60)
def heartbeat(): """ Probe the environment and figure out which user is logged in at the moment, if any """ # Get any user data we need to update update = request.values.get("update", None) if update: update = json.loads(update) for user_id, data in update.items(): update_user_data(user_id, data) data = {"users": get_users()} return json.dumps(data)
def email_uncompleted_upto_today(dbo): """ Goes through all system users and emails them their diary for the day - unless the option is turned off. """ if not configuration.email_diary_notes(dbo): return l = dbo.locale try: allusers = users.get_users(dbo) except Exception as err: al.error("failed getting list of users: %s" % str(err), "diary.email_uncompleted_upto_today", dbo) # Grab list of diary notes for today notes = get_uncompleted_upto_today(dbo) # If we don't have any, bail out if len(notes) == 0: return # Go through all user to see if we have relevant notes for them for u in allusers: if u.emailaddress and u.emailaddress.strip() != "": s = "" totalforuser = 0 for n in notes: # Is this note relevant for this user? if (n.diaryforname == "*") \ or (n.diaryforname == u.username) \ or (u.roles.find(n.diaryforname) != -1): s += i18n.python2display(l, n.diarydatetime) + " " s += n.subject if n.linkinfo is not None and n.linkinfo != "": s += " / " + n.linkinfo s += "\n" + n.note + "\n\n" totalforuser += 1 if totalforuser > 0: al.debug( "got %d notes for user %s" % (totalforuser, u.username), "diary.email_uncompleted_upto_today", dbo) utils.send_email(dbo, configuration.email(dbo), u.emailaddress, "", "", i18n._("Diary notes for: {0}", l).format( i18n.python2display(l, dbo.now())), s, exceptions=False)
def test_request_response_with_patcher(self): """Mocking using a patcher""" mock_get_patcher = patch('users.requests.get') # Start patching 'requests.get'. mock_get = mock_get_patcher.start() # Configure the mock to return a response with status code 200. mock_get.return_value.status_code = 200 # Call the service, which will send a request to the server. response = get_users() # Stop patching 'requests'. mock_get_patcher.stop() # Assert that the request-response cycle completed successfully. self.assertEqual(response.status_code, 200)
def main() -> None: # RedBlackTree zamenjaj s svojim drevesom, ter preveri, kako deluje start = process_time() test_adding(SkipList(), 10000) print("Simple test: {time} s".format(time=(process_time() - start))) start = process_time() count_adding(SkipList(), 1000) print("Simple test: {time} s".format(time=(process_time() - start))) N = 10**4 users = get_users(add_naive=False) for user in users: try: test_adding(user.tree(), N, True) count_adding(user.tree(), N, False) print("SUCCESS: ", user.user_name) except Exception as e: print("FAILED:", user.user_name, e)
def __init__(self, test_type, users, author): self.NextState = { '1':{ '1': {'1':'5'} }, '2':{ '1':{'1':'2'}, '2':{'1':'5','2':'1'} }, #High '3':{ '1':{'1':'3'}, '3':{'1':'5','2':'1'} }, #Severe '4':{ '1':{'1':'3'}, '3':{'1':'4','2':'1'}, '4':{'1':'5','2':'1'} } } self.author = author self.test_type = test_type self.current_state = enums.State.BEGIN self.users_approved = [] # Sets used for conditional fsm procedures self.lvl_one_mgr_set = set([]) self.all_mgr_set = set([]) self.cur_mgr_set = set([]) self.ceo_set = set([]) for usr in users.get_users(): if usr.group is self.author.group - 1: self.lvl_one_mgr_set.add(usr.uid) elif usr.group > self.author.group: self.all_mgr_set.add(usr.uid) self.cur_mgr_set.add(usr.uid) elif usr.group is 1: self.ceo_set.add(usr.uid)
def org_tags(dbo, username): """ Generates a list of tags from the organisation and user info """ u = users.get_users(dbo, username) realname = "" email = "" if len(u) > 0: u = u[0] realname = u["REALNAME"] email = u["EMAILADDRESS"] tags = { "ORGANISATION" : configuration.organisation(dbo), "ORGANISATIONADDRESS" : configuration.organisation_address(dbo), "ORGANISATIONTELEPHONE" : configuration.organisation_telephone(dbo), "DATE" : python2display(dbo.locale, now(dbo.timezone)), "USERNAME" : username, "USERREALNAME" : realname, "USEREMAILADDRESS" : email } return tags
def welcome(): id = users.user_id() nimi = users.user_firstname(users.user_all(id)) if users.is_admin(id): courselist = courses.get_courses() userlist = users.get_users() userlist.sort(key=lambda x: x[5]) answerList = questions.get_answers() return render_template("welcome_admin.html", name = nimi, courses = courselist, \ users = userlist, answers = answerList) elif users.is_teacher(id): course = courses.get_course_with_teacher(id) return render_template("welcome_teacher.html", id=id, name=nimi, courses=course) elif users.is_student(id): mycourselist = students.get_courses(id) courselist = courses.get_courses() return render_template("welcome_student.html", id = id, name = nimi, courses = courselist,\ mycourses = mycourselist) else: return render_template("error.html", message="Jokin meni vikaan")
def edit_repo(id): assert_repo_permission(id, 'is_owner') if request.method == 'GET': return render_repo_details(id, 'repo_edit.html') # commit changes permissions = ['is_owner', 'can_read', 'can_write', 'can_rewind', 'can_create_tag', 'can_modify_tag'] for user in users.get_users(): user_permissions = {} if 'exists_' + str(user['user_id']) not in request.form: continue for permission in permissions: name = '{0}_{1}'.format(permission, user['user_id']) value = name in request.form user_permissions[permission] = value repos.update_repo_acls( repo_id=id, user_id=user['user_id'], **user_permissions ) return redirect(url_for('edit_repo', id=id))
def edit_repo(id): assert_repo_permission(id, 'is_owner') if request.method == 'GET': return render_repo_details(id, 'repo_edit.html') # commit changes permissions = [ 'is_owner', 'can_read', 'can_write', 'can_rewind', 'can_create_tag', 'can_modify_tag' ] for user in users.get_users(): user_permissions = {} if 'exists_' + str(user['user_id']) not in request.form: continue for permission in permissions: name = '{0}_{1}'.format(permission, user['user_id']) value = name in request.form user_permissions[permission] = value repos.update_repo_acls(repo_id=id, user_id=user['user_id'], **user_permissions) return redirect(url_for('edit_repo', id=id))
def get_next_port(): from users import get_users u = get_users() ports = map(int, [user_data['Config'].get('LocalPort', 0) for user_data in u]) last_port = max(ports) or 25000 return last_port + 1
def test_users(input_, expected): assert get_users(input_) == expected
def list_users(): # return list of users userlist = users.get_users() return render_template('users.html', userlist=userlist)
def test_request_response(self): response = get_users() # Assert that the request-response cycle completed successfully with status code 200. self.assertEqual(response.status_code, 200)
def leaderboard(): users = get_users().sort('score', -1) return render_template('leaderboard.html', users=users)
def GET(self): if (web.config._session.roleid != 1): raise web.seeother('/') userlist = users.get_users() utable = render.user_list(userlist) return render_page(utable)
def calculate(): for user in get_users(): calculate_score(user) return ''
def test_response_status(self): response = get_users() print('Response Status: {}'.format(response.status_code)) self.assertEqual(response.status_code, 200)
def test_response_time(self): responseTime = get_users().elapsed.total_seconds() print('Response Time: {}'.format(responseTime)) # 200milliseconds = 0.2 seconds self.assertLess(responseTime,0.2)