def test_klassen(self): s = webuntis.Session(**stub_session_parameters) def getKlassen(url, jsondata, headers): assert not jsondata['params'] return {'result': {}} with mock_results({'getKlassen': getKlassen}): kl = s.klassen() assert type(kl) is webuntis.objects.KlassenList assert not kl
def test_klassen_with_schoolyear(self): s = webuntis.Session(**stub_session_parameters) yearid = 1232 def getKlassen(url, jsondata, headers): assert jsondata['params']['schoolyearId'] == yearid return {'result': {}} with mock_results({'getKlassen': getKlassen}): kl = s.klassen(schoolyear=yearid) assert type(kl) is webuntis.objects.KlassenList assert not kl
def open_session(): """ __init__(): opens up the webuntis session. :return: """ session = webuntis.Session(username='******', password='******', server='https://urania.webuntis.com', school='htl3r', useragent='Webuntis Test').login() return session
def getSession(config): """Return Session object""" session = wu.Session( server = config.server, username = config.username, password = config.password, school = config.school, useragent = 'webuntis-ics-calendar' ) return session
def test_login_successful(self): session_params = dict(stub_session_parameters) del session_params['jsessionid'] s = webuntis.Session(**session_params) with mock.patch( 'webuntis.Session._request', return_value={'sessionId': '123456'} ) as mock_obj: s.login() assert s.config['jsessionid'] == '123456' assert mock_obj.call_count == 1
def main() -> None: # setting locale to the default language # this is used for the date format in the mails. # https://docs.python.org/3/library/locale.html#locale.setlocale locale.setlocale(locale.LC_ALL, '') logging.debug("reading credentials from config file") config = configparser.ConfigParser() config.read("config.ini") cred = config["credentials"] logging.debug("checking environment variables") days = int(os.getenv("DAYS", 5)) code = os.getenv("CODE", "cancelled") recipient = os.getenv("RECIPIENT", None) if recipient is None: print("Provide a recipient in env var RECIPIENT") exit(1) logging.debug("creating session object and connecting") sess = webuntis.Session(username=cred["username"], password=cred["password"], server=cred['server'], useragent="WebUntis Reminder", school=cred['school']) sess.login() logging.debug("creating mailer") mailconf = config['mail'] mailer = Mailer(mailconf['host'], mailconf['user'], mailconf['pass'], mailconf['sender'], recipient) mailbody_template = """ Der folgende Unterricht fällt für die {klasse} in den folgenden {days} Tagen aus. """ for klasse in sess.klassen(): logging.debug("Checking Klasse %s", klasse.name) timet = FilteredTimetable(sess, klasse.name, days, code) if not timet.is_empty(): logging.debug("sending mail for %s", klasse.name) timet.send_via_mail(mailer, "Unterrichtsausfall für " + klasse.name, mailbody_template) sess.logout()
def test_context_manager(self): session_params = dict(stub_session_parameters) del session_params['jsessionid'] s = webuntis.Session(**session_params) with s as mgr: assert mgr is s assert 'jsessionid' not in s.config sessionid = 'foobar_session' with mock.patch('webuntis.Session._request', return_value={'sessionId': sessionid}) as mock_obj: with s.login() as msg: assert mgr is s assert s.config['jsessionid'] == sessionid
def test_login_repeat_not_logged_in(self): s = webuntis.Session(**stub_session_parameters) retry_amount = 5 calls = [] expected_calls = ( ['getCurrentSchoolyear', 'logout', 'authenticate'] * (retry_amount + 1) )[:-2] def authenticate(url, jsondata, headers): calls.append(jsondata['method']) return { 'result': {'sessionId': 'Foobar_session_' + jsondata['id']} } def getCurrentSchoolyear(url, jsondata, headers): calls.append(jsondata['method']) return { 'error': {'code': -8520, 'message': 'Not logged in!'} } def logout(url, jsondata, headers): calls.append(jsondata['method']) return { 'result': {'bla': 'blub'} # shouldn't matter } methods = { 'authenticate': authenticate, 'getCurrentSchoolyear': getCurrentSchoolyear, 'logout': logout } with mock_results(methods): with mock.patch.dict( s.config, {'login_repeat': retry_amount} ): self.assertRaises(webuntis.errors.NotLoggedInError, s._request, 'getCurrentSchoolyear') assert calls == expected_calls
def get_webuntis(cred, start, end): data = {} s = webuntis.Session(username=cred["username"], password=cred["password"], server=cred["server"], school=cred["school"], useragent=cred["useragent"]).login() old_stderr = sys.stderr sys.stderr = sys.stdout try: if "class" in cred: klasse = s.klassen().filter(name=cred["class"])[0] timetable = s.timetable(start=start, end=end, klasse=klasse) elif "surname" in cred and "fore_name" in cred: student = s.get_student(surname=cred["surname"], fore_name=cred["fore_name"]).id timetable = s.timetable(start=start, end=end, student=student) else: raise AttributeError( "WebUntis is not configured correctly. Neither class nor surname&fore_name is configured." ) timetable = sorted(timetable, key=lambda lesson: lesson.start) for lesson in timetable: if lesson.code != "cancelled": st = lesson.start.hour + lesson.start.minute / 60.0 en = lesson.end.hour + lesson.end.minute / 60.0 if lesson.start.weekday() in data: data[lesson.start.weekday()] += [(st, en)] else: data[lesson.start.weekday()] = [(st, en)] except: print("Start and End Date not in the same school year.") sys.stderr = old_stderr return data
def test_timetable_invalid_obj_given(self): s = webuntis.Session(**stub_session_parameters) start = 20120303 end = 20120304 self.assertRaisesRegex(TypeError, 'by keyword', s.timetable, start=start, end=end) self.assertRaisesRegex(TypeError, 'by keyword', s.timetable, start=start, end=end, klasse=123, teacher=124) self.assertRaisesRegex(TypeError, 'by keyword', s.timetable, start=start, end=end, foobar=128)
def getschooldatafor(monday): # TODO: actually get correct data, maybe even with the additional information friday = monday + datetime.timedelta(days=4) print("getting subjects from " + str(monday) + " to " + str(friday)) session = webuntis.Session(server='mese.webuntis.com', username=username, password=password, school='IT-Schule Stuttgart', useragent='UserAgent') session.login() index = 0 klasse = session.klassen().filter(name="E2FI5")[0] tt = session.timetable(klasse=klasse, start=monday, end=friday) # for element in tt: # print(element.subjects) subjectsthisweek = {} for element in tt: subj = str(element.subjects) + ": " subj = subj.replace('[', '') subj = subj.replace(']', '') if subj in subjectsthisweek and element.code != "cancelled": subjectsthisweek[subj][0] += 1 elif element.code != "cancelled": subjectsthisweek[subj] = [0, ""] for subj in subjectsthisweek: subjectsthisweek[subj][0] *= 2 session.logout() return subjectsthisweek
def test_examtype(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock(u'getExamTypes'): et = s.exam_types() assert type(et) is webuntis.objects.ExamTypeList
def test_students(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getStudents'): st = s.students() assert type(st) is webuntis.objects.StudentsList assert len(st) == 0
def test_timegridUnits(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getTimegridUnits'): st = s.timegrid_units() assert type(st) is webuntis.objects.TimegridObject
def test_lastImportTime(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock(u'getLatestImportTime'): li = s.last_import_time() assert type(li) is webuntis.objects.TimeStampObject
"original_teachers": convertOriginalTeachers(hour), "rooms": convertRooms(hour), "original_rooms": convertOriginalRooms(hour), "start": hour.start, "end": hour.end, "subjects": convertSubjects(hour), "klassen": convertKlassen(hour), "code": hour.code }) table.sort(key=sort) return table with webuntis.Session( username='', # username password='', # password server='tipo.webuntis.com', school='TBZ Mitte Bremen', useragent='E-Paper AG').login() as s: with open("test", "wb") as file: data = {} rooms = s.rooms().filter(name=requestedRooms) print(rooms) for room in rooms: tt = s.timetable(room=room, start=today, end=today) data.update({room.name: timetableToPy(tt)}) pickle.dump(data, file) print(data)
def test_use_cache(self): s = webuntis.Session(use_cache=True, **stub_session_parameters) assert webuntis.utils.result_wrapper.session_use_cache s = webuntis.Session(use_cache=False, **stub_session_parameters) assert not webuntis.utils.result_wrapper.session_use_cache
def test_schoolyears(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock(u'getSchoolyears'): sch = s.schoolyears() assert type(sch) is webuntis.objects.SchoolyearList assert not sch
def test_holidays(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getHolidays'): hol = s.holidays() assert type(hol) is webuntis.objects.HolidayList assert not hol
def test_departments(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getDepartments'): dep = s.departments() assert type(dep) is webuntis.objects.DepartmentList assert not dep
def test_custom_cachelen(self): s = webuntis.Session(cachelen=20, **stub_session_parameters) assert s.cache._maxlen == 20
with open(CURRENT + "config.json") as FILE: DATA = json.load(FILE) global USERNAME, PASSWORD, SERVER, SCHOOL, STUDENTID USERNAME = DATA["username"] PASSWORD = DATA["password"] SERVER = DATA["server"] SCHOOL = DATA["school"] STUDENTID = DATA["webuntis_id"] try: if path.exists(CURRENT + "wrong_pass"): print("Last time wrong password, not trying again") exit() with webuntis.Session(username=USERNAME, password=PASSWORD, server=SERVER, school=SCHOOL, useragent='Chrome').login() as s: LESSON_REQ = s.timetable(student=STUDENTID, start=TODAY, end=END) from string import digits remove_digits = str.maketrans('', '', digits) delete_events() for lesson in LESSON_REQ: if lesson.code != 'cancelled': lesson.rooms = str(lesson.rooms).replace("[", "") lesson.rooms = str(lesson.rooms).replace("]", "") lesson.subjects = str(lesson.subjects).replace("[", "") lesson.subjects = str(lesson.subjects).replace("]", "") if (lesson.start.strftime("%H:%M") == "08:20"): s = "1"
def test_exams(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock(u'getExams'): ex = s.exams(start=1, end=2, exam_type_id=1) assert type(ex) is webuntis.objects.ExamsList
def test_subjects(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getSubjects'): sb = s.subjects() assert type(sb) is webuntis.objects.SubjectList assert not sb
def test_timetableWithAbsences(self): s = webuntis.Session(**stub_session_parameters) with self.absences_result_mock('getTimetableWithAbsences'): ex = s.timetable_with_absences(start=1, end=2) assert type(ex) is webuntis.objects.AbsencesList
def test_teachers(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getTeachers'): te = s.teachers() assert type(te) is webuntis.objects.TeacherList assert not te
def test_class_reg_events(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getClassregEvents'): ex = s.class_reg_events(start=1, end=2) assert type(ex) is webuntis.objects.ClassRegEventList
def test_statusdata(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock('getStatusData'): st = s.statusdata() assert type(st) is webuntis.objects.StatusData
def test_rooms(self): s = webuntis.Session(**stub_session_parameters) with self.noop_result_mock(u'getRooms'): ro = s.rooms() assert type(ro) is webuntis.objects.RoomList assert not ro
def getTimetable(day=datetime.date.today()): s = webuntis.Session(server='neilo.webuntis.com', school='bg-brg-keimgasse', username='', password='', useragent='Odis-WebUntis-Scraper') s.login() lesson_starttimes = [ datetime.datetime.combine(day, datetime.time(hour=8, minute=0)), datetime.datetime.combine(day, datetime.time(hour=8, minute=55)), datetime.datetime.combine(day, datetime.time(hour=10, minute=0)), datetime.datetime.combine(day, datetime.time(hour=10, minute=55)), datetime.datetime.combine(day, datetime.time(hour=11, minute=50)), datetime.datetime.combine(day, datetime.time(hour=12, minute=45)), datetime.datetime.combine(day, datetime.time(hour=14, minute=0)), datetime.datetime.combine(day, datetime.time(hour=14, minute=50)), datetime.datetime.combine(day, datetime.time(hour=15, minute=40)), datetime.datetime.combine(day, datetime.time(hour=16, minute=30)) ] # get list of subjects and timetable for 1 day suj = s.subjects() klasse = s.klassen().filter(name='7m')[0] tt = s.timetable(klasse=klasse, start=day, end=day) s.logout() # sort lessons by starttime lessons_sorted = [] for time in lesson_starttimes: lessons_sorted.append(tt.filter(start=time)) # result array timetable = [] for lessons in lessons_sorted: l = len(lessons) # free if (l == 0): timetable.append([]) else: to_append = [] for i in range(len(lessons)): code = lessons[i].code # normal if (code == None): to_append.append( suj.filter(id=lessons[i].subjects[0].id)[0].name) else: if (code == "cancelled"): to_append.append('--' + suj.filter( id=lessons[i].subjects[0].id)[0].name) if (code == "irregular"): try: to_append.append('++' + suj.filter( id=lessons[i].subjects[0].id)[0].name) except IndexError: to_append.append("failed") timetable.append(to_append) return timetable