Example #1
0
 def test_user_open_the_reference_book(self):
     """No test placeholder."""
     self.user.login(self.server, self.login, self.password)
     main_window = self.user.driver.current_window_handle
     courses = self.user.driver.find_elements(
         By.CLASS_NAME,
         'tutor-course-item'
     )
     course_number = 0 if len(courses) <= 1 \
         else randint(1, len(courses)) - 1
     Assignment.scroll_to(self.user.driver, courses[course_number])
     self.user.select_course(title=courses[course_number].text)
     was_successful = 'courses' in self.user.driver.current_url or \
         'list' in self.user.driver.current_url or \
         'calendar' in self.user.driver.current_url
     assert(was_successful), 'Failed to select course'
     self.user.view_reference_book()
     self.user.driver.switch_to_window(self.user.driver.window_handles[1])
     WebDriverWait(self.user.driver, 60).until(
         expect.presence_of_element_located(
             (By.CLASS_NAME, 'center-panel')
         )
     )
     assert('contents' in self.user.driver.current_url or
            'books' in self.user.driver.current_url), \
         'Failed to open the reference or WebView book.'
     self.user.driver.close()
     self.user.driver.switch_to_window(main_window)
     was_successful = 'courses' in self.user.driver.current_url or \
         'list' in self.user.driver.current_url or \
         'calendar' in self.user.driver.current_url
     assert(was_successful), 'Failed to return to the primary browser tab'
Example #2
0
 def test_user_open_the_reference_book_208(self):
     """Open the reference view of the textbook."""
     self.user.login(self.server, self.login, self.password)
     main_window = self.user.driver.current_window_handle
     courses = self.user.get_course_list()
     course_number = 0 if len(courses) <= 1 \
         else randint(1, len(courses)) - 1
     Assignment.scroll_to(self.user.driver, courses[course_number])
     self.user.select_course(
         title=courses[course_number].get_attribute('data-title'))
     url = self.user.current_url()
     was_successful = 'course' in url or \
         'list' in url or \
         'calendar' in url
     print('%s in %s == %s' %
           ('(course,list,calendar)', url, was_successful))
     assert (was_successful), 'Failed to select course'
     self.user.view_reference_book()
     self.user.sleep(1)
     self.user.driver.switch_to_window(self.user.driver.window_handles[1])
     WebDriverWait(self.user.driver, 60).until(
         expect.presence_of_element_located(
             (By.CLASS_NAME, 'center-panel')))
     assert('contents' in self.user.current_url() or
            'books' in self.user.current_url()), \
         'Failed to open the reference or WebView book.'
     self.user.driver.close()
     self.user.driver.switch_to_window(main_window)
     was_successful = 'course' in self.user.current_url() or \
         'list' in self.user.current_url() or \
         'calendar' in self.user.current_url()
     assert (was_successful), 'Failed to return to the primary browser tab'
Example #3
0
 def get_book_sections(self):
     """Return a list of book sections."""
     self.goto_calendar()
     self.page.wait_for_page_load()
     self.driver.find_element(By.ID, 'add-assignment').click()
     self.wait.until(
         expect.element_to_be_clickable(
             (By.LINK_TEXT, 'Add Reading')
         )
     ).click()
     self.page.wait_for_page_load()
     selector = self.driver.find_element(By.ID, 'reading-select')
     Assignment.scroll_to(self.driver, selector)
     sleep(1.0)
     selector.click()
     self.page.wait_for_page_load()
     for chapter in self.driver.find_elements(By.XPATH,
                                              '//a[@href="#" and span]'):
         if chapter.get_attribute('aria-expanded') != 'true':
             Assignment.scroll_to(self.driver, chapter)
             sleep(0.25)
             chapter.click()
     sections = self.driver.find_elements(
         By.XPATH,
         '//div[@class="section"]/span[@class="chapter-section"]'
     )
     section_list = []
     for section in sections:
         section_list.append(section.text)
     self.goto_calendar()
     return section_list
Example #4
0
 def get_month_year(self):
     """Break a date string into a month year tuple."""
     calendar_heading = self.find(By.CSS_SELECTOR, '.calendar-header-label')
     Assignment.scroll_to(self.driver, calendar_heading)
     calendar_date = calendar_heading.text
     month, year = calendar_date.split(' ')
     return self.get_month_number(month), int(year)
Example #5
0
 def test_user_select_course_by_title(self):
     """Select a course by its title."""
     self.user.login(self.server, self.login, self.password)
     print(self.user.current_url())
     courses = self.user.driver.find_elements(
         By.CLASS_NAME,
         'tutor-course-item'
     )
     course_number = 0 if len(courses) <= 1 \
         else randint(1, len(courses)) - 1
     title = courses[course_number].text
     Assignment.scroll_to(self.user.driver, courses[course_number])
     self.user.select_course(title=title)
     was_successful = 'courses' in self.user.driver.current_url or \
         'list' in self.user.driver.current_url or \
         'calendar' in self.user.driver.current_url or \
         'contents' in self.user.driver.current_url
     assert(was_successful), \
         'Failed to select course in URL: %s' % self.user.driver.current_url
     if 'contents' in self.user.driver.current_url:
         return
     course_name = self.user.driver.find_element(
         By.CLASS_NAME,
         'course-name'
     ).text
     assert(title == course_name), 'Failed to select course "%s"' % title
Example #6
0
 def test_assignment_open_assignment_menu(self):
     """Test opening the assignment creation menu."""
     self.driver.get('https://' + os.getenv('SERVER_URL'))
     self.driver.find_element(By.CSS_SELECTOR, '.login').click()
     login = self.driver.find_element(By.CSS_SELECTOR,
                                      '#login_username_or_email')
     login.click()
     login.send_keys(os.getenv('TEACHER_USER'))
     self.driver.find_element(By.CSS_SELECTOR, '[type=submit]').click()
     password = self.driver.find_element(By.CSS_SELECTOR, '#login_password')
     password.click()
     password.send_keys(os.getenv('TEACHER_PASSWORD'))
     self.driver.find_element(By.CSS_SELECTOR, '[type=submit]').click()
     courses = self.driver.find_elements(
         By.CSS_SELECTOR,
         '.my-courses-current [data-course-course-type=tutor]')
     courses[randint(0, len(courses) - 1)].click()
     try:
         self.wait.until(
             expect.element_to_be_clickable((
                 By.XPATH,
                 '//button[contains(text(),"For extra credit")]'))).click()
         self.find(By.CLASS_NAME, 'btn-primary').click()
     except Exception:
         pass
     menu = self.driver.find_element(By.CLASS_NAME, 'sidebar-toggle')
     Assignment.scroll_to(self.driver, menu)
     if 'open' not in menu.get_attribute('class'):
         time.sleep(2)
         menu.click()
     self.assignment.open_assignment_menu(self.driver)
     assert ('open' in menu.get_attribute('class'))
Example #7
0
    def finish_reading_assignment(self, assignment_identifier):
        """
        HELPER FUNCTION
        Arguments:
        -assignment_identifier : a string that will identify the assignment
        (can either be the whole name or portion the name)

        Will complete the assignment, so that we get to the completion report

        :param assignment_identifier: (string) name or identifier that we
        can use to find the assignment of interest on the student course dashboard
        """
        while (True):

            # this is for progressing through the actual reading itself
            while ('arrow right' in self.student.driver.page_source):
                self.student.find(
                    By.XPATH, "//a[contains(@class,'arrow') " +
                    "and contains(@class,'right')]").click()

            # come here if multiple choice question
            if ('exercise-multiple-choice' in self.student.driver.page_source):

                answers = self.student.find(By.CLASS_NAME, 'answer-letter')
                self.student.sleep(0.8)
                rand = randint(0, len(answers) - 1)
                answer = chr(ord('a') + rand)
                Assignment.scroll_to(self.student.driver, answers[0])
                if answer == 'a':
                    self.student.driver.execute_script(
                        'window.scrollBy(0, -160);')
                elif answer == 'd':
                    self.student.driver.execute_script(
                        'window.scrollBy(0, 160);')
                answers[rand].click()

                self.student.wait.until(
                    expect.element_to_be_clickable(
                        (By.XPATH, '//button[contains(@class,"async-button")' +
                         ' and contains(@class,"continue")]'))).click()
                self.student.sleep(5)
                page = self.student.driver.page_source
                assert ('question-feedback bottom' in page), \
                    'Did not submit MC'

            # come here if free response question
            elif ('textarea' in self.student.driver.page_source):
                self.student.find(
                    By.TAG_NAME,
                    'textarea').send_keys('An answer for this textarea')
                self.student.sleep(1)
                self.student.wait.until(
                    expect.element_to_be_clickable(
                        (By.XPATH, '//button[contains(@class,"async-button")' +
                         ' and contains(@class,"continue")]')))
    def test_teacher_add_a_new_open_event_all_periods_162172(self):
        self.ps.test_updates['name'] = 'tutor_event_teacher' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = \
            ['tutor', 'event', 'teacher', '162172']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        assignment_name = 'event_001_%d' % (randint(100, 999))
        assignment = Assignment()

        # Open Add Reading page
        self.teacher.assign.open_assignment_menu(self.teacher.driver)
        self.teacher.find(By.LINK_TEXT, 'Add Event').click()
        assert ('event/new' in self.teacher.current_url()), \
            'not at add event screen'

        # Find and fill in title
        self.teacher.wait.until(
            expect.element_to_be_clickable(
                (By.ID, 'reading-title'))).send_keys(assignment_name)

        # Fill in description
        self.teacher.find(
            By.XPATH,
            '//textarea[contains(@class, "form-control")]').send_keys(
                'description')

        # Set date
        today = datetime.date.today()
        end = randint(1, 5)
        opens_on = today.strftime(
            '%m/%d/%Y')  # make the start date today so it will be open
        closes_on = (today + datetime.timedelta(days=end)) \
            .strftime('%m/%d/%Y')
        assignment.assign_periods(self.teacher.driver,
                                  {'all': (opens_on, closes_on)})

        # publish
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//button[contains(@class,"-publish")]'))).click()
        try:
            self.teacher.find(
                By.XPATH,
                '//label[contains(text(),"{0}")]'.format(assignment_name))
        except NoSuchElementException:
            self.teacher.find(
                By.XPATH,
                '//a[contains(@class,"header-control next")]').click()
            self.teacher.find(
                By.XPATH,
                '//label[contains(text(),"{0}")]'.format(assignment_name))

        self.ps.test_updates['passed'] = True
Example #9
0
 def test_assignment_class_method_send_keys(self):
     """Test send keystrokes individually."""
     self.driver.get('https://www.randomlists.com/random-words')
     self.driver.find_element(By.NAME, 'submit').click()
     word_list = self.driver.find_elements(By.CSS_SELECTOR, '.crux')
     word = word_list[randint(0, len(word_list) - 1)].text
     self.driver.get('https://duckduckgo.com/')
     search = self.driver.find_element(By.ID, 'search_form_input_homepage')
     Assignment.send_keys(self.driver, search, word + '\n')
     search = self.driver.find_element(By.ID, 'search_form_input')
     assert (word in self.driver.page_source.lower()), 'Word not searched'
Example #10
0
 def test_assignment_class_method_scroll_to(self):
     """Test page scrolling to show aspecific element."""
     self.driver.set_window_size(1024, 768)
     self.driver.get('https://www.google.com/#q=openstax')
     time.sleep(1)
     last_link = self.driver.find_elements(By.CSS_SELECTOR, 'div.g')
     assert (last_link), 'No elements found'
     last_link = last_link[-2].find_element(By.TAG_NAME, 'a')
     with self.assertRaises(WebDriverException):
         last_link.click()
     Assignment.scroll_to(self.driver, last_link, True)
     time.sleep(3)
     last_link.click()
 def setUp(self):
     """Pretest settings."""
     self.ps = PastaSauce()
     self.desired_capabilities['name'] = self.id()
     if not LOCAL_RUN:
         self.teacher = Teacher(username=os.getenv('TEACHER_USER_CC'),
                                password=os.getenv('TEACHER_PASSWORD'),
                                pasta_user=self.ps,
                                capabilities=self.desired_capabilities)
     else:
         self.teacher = Teacher(
             username=os.getenv('TEACHER_USER_CC'),
             password=os.getenv('TEACHER_PASSWORD'),
         )
     self.teacher.login()
     if 'cc-dashboard' not in self.teacher.current_url():
         courses = self.teacher.find_all(By.CLASS_NAME,
                                         'tutor-booksplash-course-item')
         assert (courses), 'No courses found.'
         if not isinstance(courses, list):
             courses = [courses]
         course_id = randint(0, len(courses) - 1)
         self.course = courses[course_id].get_attribute('data-title')
         self.teacher.select_course(title=self.course)
     self.teacher.goto_course_roster()
     try:
         section = self.teacher.find_all(
             By.XPATH, '//*[contains(@class,"nav-tabs")]//a')
         if isinstance(section, list):
             section = '%s' % section[randint(0, len(section) - 1)].text
         else:
             section = '%s' % section.text
     except Exception:
         section = '%s' % randint(100, 999)
         self.teacher.add_course_section(section)
     self.code = self.teacher.get_enrollment_code(section)
     print('Course Phrase: ' + self.code)
     self.book_url = self.teacher.find(
         By.XPATH,
         '//a[span[contains(text(),"Online Book")]]').get_attribute('href')
     self.teacher.find(By.CSS_SELECTOR, 'button.close').click()
     self.teacher.sleep(0.5)
     self.teacher.logout()
     self.teacher.sleep(1)
     self.student = Student(use_env_vars=True,
                            existing_driver=self.teacher.driver)
     self.first_name = Assignment.rword(6)
     self.last_name = Assignment.rword(8)
     self.email = self.first_name + '.' \
         + self.last_name \
         + '@tutor.openstax.org'
 def setUp(self):
     """Pretest settings."""
     self.ps = PastaSauce()
     self.desired_capabilities['name'] = self.id()
     self.teacher = Teacher(
         username=os.getenv('TEACHER_USER_CC'),
         password=os.getenv('TEACHER_PASSWORD'),
         pasta_user=self.ps,
         capabilities=self.desired_capabilities
     )
     self.teacher.login()
     if 'cc-dashboard' not in self.teacher.current_url():
         courses = self.teacher.find_all(
             By.CLASS_NAME,
             'tutor-booksplash-course-item'
         )
         assert(courses), 'No courses found.'
         if not isinstance(courses, list):
             courses = [courses]
         course_id = randint(0, len(courses) - 1)
         self.course = courses[course_id].get_attribute('data-title')
         self.teacher.select_course(title=self.course)
     self.teacher.goto_course_roster()
     try:
         section = self.teacher.find_all(
             By.XPATH,
             '//*[contains(@class,"nav-tabs")]//a'
         )
         if isinstance(section, list):
             section = '%s' % section[randint(0, len(section) - 1)].text
         else:
             section = '%s' % section.text
     except Exception:
         section = '%s' % randint(100, 999)
         self.teacher.add_course_section(section)
     self.code = self.teacher.get_enrollment_code(section)
     print('Course Phrase: ' + self.code)
     self.book_url = self.teacher.find(
         By.XPATH, '//a[span[contains(text(),"Online Book")]]'
     ).get_attribute('href')
     self.teacher.find(By.CSS_SELECTOR, 'button.close').click()
     self.teacher.sleep(0.5)
     self.teacher.logout()
     self.teacher.sleep(1)
     self.student = Student(use_env_vars=True,
                            existing_driver=self.teacher.driver)
     self.first_name = Assignment.rword(6)
     self.last_name = Assignment.rword(8)
     self.email = self.first_name + '.' \
         + self.last_name \
         + '@tutor.openstax.org'
Example #13
0
 def accept_contract(self):
     """
     Contract acceptance for Terms of Service and the Privacy Policy.
     """
     checkbox_id = 'agreement_i_agree' if 'accounts' in \
         self.current_url() else 'i_agree'
     try:
         target = self.find(By.ID, checkbox_id)
         Assignment.scroll_to(self.driver, target)
         target.click()
         target = self.find(By.ID, 'agreement_submit')
         Assignment.scroll_to(self.driver, target)
         target.click()
     except Exception as e:
         raise e
Example #14
0
 def test_add_reading_assignment_one_cancel(self):
     """Build reading assignments."""
     # Reading, one period, cancel
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     left = randint(5, 20)
     right = left + randint(1, 10)
     start_date_1 = self.teacher.date_string(day_delta=left)
     end_date_1 = self.teacher.date_string(day_delta=left + right)
     reading_options = self.teacher.get_book_sections()
     reading_start = randint(0, (len(reading_options) - 1))
     reading_end = reading_start + randint(1, 5)
     reading_list = reading_options[reading_start:reading_end]
     self.teacher.add_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'description': 'Staxing test reading - cancel',
             'periods': {
                 'First': (start_date_1, end_date_1),
             },
             'reading_list': reading_list,
             'status': 'cancel',
             'break_point': None,
         }
     )
     assert('courses' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date_1)
     time.sleep(5.0)
     with pytest.raises(NoSuchElementException):
         self.teacher.find(
             By.XPATH,
             '//label[text()="%s"]' % assignment_title
         )
Example #15
0
 def test_add_reading_assignment_all_draft(self):
     """Build reading assignments."""
     # Reading, all periods, draft
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     left = randint(5, 20)
     right = left + randint(1, 10)
     start_date_1 = self.teacher.date_string(day_delta=left)
     end_date_1 = self.teacher.date_string(day_delta=left + right)
     reading_options = self.teacher.get_book_sections()
     reading_start = randint(0, (len(reading_options) - 1))
     reading_end = reading_start + randint(1, 5)
     reading_list = reading_options[reading_start:reading_end]
     self.teacher.add_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'description': 'Staxing test reading - all periods - draft',
             'periods': {
                 'all': (start_date_1, end_date_1),
             },
             'reading_list': reading_list,
             'status': 'draft',
             'break_point': None,
         }
     )
     assert('courses' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date_1)
     reading = self.teacher.find(
         By.XPATH,
         '//label[text()="%s"]' % assignment_title
     )
     time.sleep(5.0)
     assert(reading), '%s not publishing on %s' % (assignment_title,
                                                   end_date_1)
Example #16
0
 def test_assignments(self):
     begin = (self.today + datetime.timedelta(days=0)).strftime('%m/%d/%Y')
     end = (self.today + datetime.timedelta(days=3)).strftime('%m/%d/%Y')
     # start the code example
     self.user.login()
     self.user.select_course(category='physics')
     for chap in ['ch11', 'ch12']:
         reading = 'v6.131 chapter %s' % chap
         self.user.add_assignment(
             assignment='reading',
             args={
                 'title': reading,
                 'description': 'A diagnostic assignment for %s' % chap,
                 'periods': {'all': (begin, end)},
                 'reading_list': [chap],
                 'status': 'publish',
             }
         )
         sleep(5)
     homework = 'test-hw %s' % Assignment.rword(8)
     self.user.add_assignment(
         assignment='homework',
         args={
             'title': homework,
             'description': 'An auto-test assignment',
             'periods': {'all': (begin, end)},
             'problems': {'4': None,
                          '4.1': (4, 8),
                          '4.2': 'all',
                          '4.3': ['2102@1', '2104@1', '2175'],
                          'ch5': 5,
                          'tutor': 4},
             'status': 'draft',
         }
     )
Example #17
0
    def __init__(self,
                 username,
                 password,
                 site='https://tutor-qa.openstax.org',
                 email=None,
                 email_username=None,
                 email_password=None,
                 driver_type='chrome',
                 capabilities=None,
                 pasta_user=None,
                 wait_time=DEFAULT_WAIT_TIME,
                 opera_driver='',
                 existing_driver=None,
                 **kwargs):
        """
        Base user constructor.

        username (string): website username
        password (string): website password
        site (string): website URL
        driver_type (string): web browser type
        pasta_user (PastaSauce): optional API access for saucelabs
        capabilities (dict): browser settings; copy object to avoid overwrite
            Defaults:
                DesiredCapabilities.ANDROID.copy()
                DesiredCapabilities.CHROME.copy()
                DesiredCapabilities.EDGE.copy()
                DesiredCapabilities.FIREFOX.copy()
                DesiredCapabilities.HTMLUNIT.copy()
                DesiredCapabilities.HTMLUNITWITHJS.copy()
                DesiredCapabilities.INTERNETEXPLORER.copy()
                DesiredCapabilities.IPAD.copy()
                DesiredCapabilities.IPHONE.copy()
                DesiredCapabilities.ORERA.copy()
                DesiredCapabilities.PHANTOMJS.copy()
                DesiredCapabilities.SAFARI.copy()
            Keys:
                platform
                browserName
                version
                javascriptEnabled
        wait (int): standard time, in seconds, to wait for Selenium commands
        opera_driver (string): Chromium location
        """
        self.username = username
        self.password = password
        self.url = self.url_parse(site)
        self.email = email
        self.email_username = email_username
        self.email_password = email_password
        self.assign = Assignment()
        self.course_dates = (None, None)
        super(User, self).__init__(driver_type=driver_type,
                                   capabilities=capabilities,
                                   pasta_user=pasta_user,
                                   wait_time=wait_time,
                                   opera_driver=opera_driver,
                                   existing_driver=existing_driver,
                                   **kwargs)
Example #18
0
 def answer_assessment(self):
     """Answer a Tutor assessment."""
     self.wait.until(
         expect.presence_of_element_located(
             (By.CLASS_NAME, 'openstax-question')
         )
     )
     text = chomsky(1, 500)
     wt = self.wait_time
     try:
         self.change_wait_time(3)
         text_block = self.find(By.XPATH, '//textarea')
         self.change_wait_time(wt)
         print('Enter free response')
         Assignment.send_keys(self.driver, text_block, text)
         self.find(By.CLASS_NAME, 'continue').click()
     except Exception:
         self.change_wait_time(wt)
         print('Skip free response')
     finally:
         self.page.wait_for_page_load()
     answers = self.find_all(By.CLASS_NAME, 'answer-letter')
     self.sleep(0.8)
     rand = randint(0, len(answers) - 1)
     answer = chr(ord('a') + rand)
     print('Selecting %s' % answer)
     Assignment.scroll_to(self.driver, answers[0])
     if answer == 'a':
         self.driver.execute_script('window.scrollBy(0, -160);')
     elif answer == 'd':
         self.driver.execute_script('window.scrollBy(0, 160);')
     answers[rand].click()
     self.sleep(1.0)
     self.wait.until(
         expect.element_to_be_clickable(
             (By.XPATH, '//button[span[text()="Submit"]]')
         )
     ).click()
     self.wait.until(
         expect.element_to_be_clickable(
             (By.CLASS_NAME, 'continue')
         )
     ).click()
     self.page.wait_for_page_load()
Example #19
0
 def answer_assessment(self):
     """Answer a Tutor assessment."""
     self.wait.until(
         expect.presence_of_element_located(
             (By.CLASS_NAME, 'openstax-question')
         )
     )
     text = chomsky(1, 500)
     wt = self.wait_time
     try:
         self.change_wait_time(3)
         text_block = self.driver.find_element(By.XPATH, '//textarea')
         self.change_wait_time(wt)
         print('Enter free response')
         Assignment.send_keys(self.driver, text_block, text)
         self.driver.find_element(By.CLASS_NAME, 'continue').click()
     except Exception:
         self.change_wait_time(wt)
         print('Skip free response')
     finally:
         self.page.wait_for_page_load()
     answers = self.driver.find_elements(By.CLASS_NAME, 'answer-letter')
     self.sleep(0.8)
     rand = randint(0, len(answers) - 1)
     answer = chr(ord('a') + rand)
     print('Selecting %s' % answer)
     Assignment.scroll_to(self.driver, answers[0])
     if answer == 'a':
         self.driver.execute_script('window.scrollBy(0, -160);')
     elif answer == 'd':
         self.driver.execute_script('window.scrollBy(0, 160);')
     answers[rand].click()
     self.sleep(1.0)
     self.wait.until(
         expect.element_to_be_clickable(
             (By.XPATH, '//button[span[text()="Submit"]]')
         )
     ).click()
     self.wait.until(
         expect.element_to_be_clickable(
             (By.CLASS_NAME, 'continue')
         )
     ).click()
     self.page.wait_for_page_load()
Example #20
0
 def test_user_go_to_course_list(self):
     """No test placeholder."""
     self.user.login(self.server, self.login, self.password)
     courses = self.user.driver.find_elements(
         By.CLASS_NAME,
         'tutor-course-item'
     )
     course_number = 0 if len(courses) <= 1 \
         else randint(1, len(courses)) - 1
     Assignment.scroll_to(self.user.driver, courses[course_number])
     self.user.select_course(title=courses[course_number].text)
     was_successful = 'courses' in self.user.driver.current_url or \
         'list' in self.user.driver.current_url or \
         'calendar' in self.user.driver.current_url
     assert(was_successful), 'Failed to select course'
     self.user.goto_course_list()
     course_picker = self.server + '/dashboard/'
     assert(self.user.driver.current_url == course_picker), \
         'Failed to return to the course picker'
Example #21
0
    def test_add_reading_assignment_all_publish_302(self):
        """Build reading assignments."""
        # Reading, all periods, publish
        assignment_title = 'Reading-%s' % Assignment.rword(5)

        left_delta = randint(0, 20)
        left = datetime.date.today() + datetime.timedelta(left_delta)
        # start_date_1 = self.teacher.date_string(day_delta=left_delta)
        start_date_2 = self.teacher.date_string(day_delta=left_delta + 1)
        if not self.teacher.date_is_valid(left):
            # start_date_1 = \
            #     (self.class_start_end_dates[0]) \
            #     .strftime('%m/%d/%Y')
            start_date_2 = \
                (self.class_start_end_dates[0] + datetime.timedelta(1)) \
                .strftime('%m/%d/%Y')
        right_delta = left_delta + randint(1, 10)
        right = datetime.date.today() + datetime.timedelta(right_delta)
        end_date_1 = self.teacher.date_string(day_delta=right_delta)
        end_date_2 = self.teacher.date_string(day_delta=right_delta + 1)
        if not self.teacher.date_is_valid(right):
            end_date_1 = \
                (self.class_start_end_dates[1] - datetime.timedelta(2)) \
                .strftime('%m/%d/%Y')
            end_date_2 = \
                (self.class_start_end_dates[1] - datetime.timedelta(1)) \
                .strftime('%m/%d/%Y')
        print('Left: %s  Right: %s' % (left, right))
        # self.book_sections = self.teacher.get_book_sections()
        reading_start = randint(0, (len(self.book_sections) - 1))
        reading_end = reading_start + randint(1, 5)
        reading_list = self.book_sections[reading_start:reading_end]
        self.teacher.add_assignment(
            assignment='reading',
            args={
                'title': assignment_title,
                'description': 'Staxing test reading - all periods - publish',
                'periods': {
                    # '1st': (start_date_1, end_date_1),
                    'all': (start_date_2, end_date_2),
                },
                'reading_list': reading_list,
                'status': 'publish',
                'break_point': None,
            })
        assert('course' in self.teacher.current_url()), \
            'Not at dashboard'
        time.sleep(2.0)
        self.teacher.rotate_calendar(end_date_1)
        reading = self.teacher.find(By.XPATH,
                                    '//label[text()="%s"]' % assignment_title)
        time.sleep(5.0)
        assert (reading), '%s not publishing on %s' % (assignment_title,
                                                       end_date_2)
Example #22
0
 def setUp(self):
     """Pretest settings."""
     self.assignment = Assignment()
     option_set = options.Options()
     option_set.add_argument('disable-infobars')
     option_set.add_argument('enable-devtools-experiments')
     option_set.add_argument('disable-search-geolocation-disclosure')
     if 'headless' in DRIVER:
         option_set.add_argument('headless')
     option_set.add_experimental_option(
         'prefs', {
             'credentials_enable_service': False,
             'profile': {
                 'password_manager_enabled': False
             }
         })
     if 'chrome' in DRIVER or 'headless' in DRIVER:
         self.driver = webdriver.Chrome(chrome_options=option_set)
     self.wait = WebDriverWait(self.driver, 15)
     self.driver.implicitly_wait(1)
Example #23
0
 def get_book_sections(self):
     """Return a list of book sections."""
     print('Enter: Get Book Sections')
     print('Retrieve the book section list')
     sleep(1)
     self.goto_calendar()
     self.page.wait_for_page_load()
     self.assign.open_assignment_menu(self.driver)
     print('Use Reading index')
     self.wait.until(
         expect.element_to_be_clickable(
             (By.LINK_TEXT, 'Add Reading')
         )
     ).click()
     self.page.wait_for_page_load()
     selector = self.find(By.ID, 'reading-select')
     Assignment.scroll_to(self.driver, selector)
     selector.click()
     self.page.wait_for_page_load()
     print('Open the entire book')
     for chapter in self.find_all(By.CSS_SELECTOR,
                                  'div.chapter-heading > a'):
         if chapter.get_attribute('aria-expanded') != 'true':
             Assignment.scroll_to(self.driver, chapter)
             sleep(0.25)
             chapter.click()
     print('Get all sections')
     sections = self.find_all(
         By.CSS_SELECTOR, 'div.section span.chapter-section')
     print('Put the list together')
     section_list = []
     section_string = ''
     for section in sections:
         section_list.append(section.text)
         section_string += ' %s' % section.text
     print('Section options: %s' % section_string)
     print('Return to the dashboard')
     self.goto_calendar()
     print('Exit: Get Book Sections')
     return section_list
Example #24
0
    def test_delete_assignment_307(self):
        """No test placeholder."""
        assignment_title = 'Reading-%s' % Assignment.rword(5)
        left_delta = randint(0, 20)
        left = datetime.date.today() + datetime.timedelta(left_delta)
        start_date = self.teacher.date_string(day_delta=left_delta)
        if not self.teacher.date_is_valid(left):
            start_date = \
                (self.class_start_end_dates[0]) \
                .strftime('%m/%d/%Y')
        right_delta = left_delta + randint(1, 10)
        right = datetime.date.today() + datetime.timedelta(right_delta)
        end_date = self.teacher.date_string(day_delta=right_delta)
        if not self.teacher.date_is_valid(right):
            end_date = \
                (self.class_start_end_dates[1] - datetime.timedelta(2)) \
                .strftime('%m/%d/%Y')
        self.teacher.add_assignment(assignment='reading',
                                    args={
                                        'title': assignment_title,
                                        'periods': {
                                            'all': (start_date, end_date),
                                        },
                                        'reading_list': ['1', '1.1'],
                                        'status': 'publish',
                                        'break_point': None,
                                    })
        assert('course' in self.teacher.current_url()), \
            'Not at dashboard'
        self.teacher.rotate_calendar(end_date)
        reading = self.teacher.find(By.XPATH,
                                    '//label[text()="%s"]' % assignment_title)
        print('Waiting for publish')

        time.sleep(5.0)
        assert(reading), \
            '%s not publishing on %s' % (assignment_title, end_date)
        self.teacher.delete_assignment(assignment='reading',
                                       args={
                                           'title': assignment_title,
                                           'periods': {
                                               'all': (start_date, end_date),
                                           },
                                       })
        self.teacher.rotate_calendar(end_date)
        time.sleep(5.0)
        try:
            self.teacher.find(By.XPATH,
                              '//label[text()="%s"]' % assignment_title)
            assert (False), '%s still exists' % assignment_title
        except Exception:
            pass
Example #25
0
 def test_delete_assignment(self):
     """No test placeholder."""
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     start_date = self.teacher.date_string(day_delta=1)
     end_date = self.teacher.date_string(day_delta=3)
     self.teacher.add_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'periods': {
                 'all': (start_date, end_date),
             },
             'reading_list': ['1', '1.1'],
             'status': 'draft',
             'break_point': None,
         }
     )
     assert('courses' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date)
     reading = self.teacher.find(
         By.XPATH,
         '//label[text()="%s"]' % assignment_title
     )
     time.sleep(5.0)
     assert(reading), \
         '%s not publishing on %s' % (assignment_title, end_date)
     new_date = start_date.split('/')
     new_date = '%s/%s' % (int(new_date[0]), int(new_date[1]))
     self.teacher.wait.until(
         expect.presence_of_element_located(
             (By.XPATH,
              '//label[@data-title="%s" and @data-opens-at="%s"]' %
              (assignment_title, new_date))
         )
     )
     self.teacher.delete_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'periods': {
                 'all': (start_date, end_date),
             },
         }
     )
     self.teacher.rotate_calendar(end_date)
     time.sleep(5.0)
     with pytest.raises(NoSuchElementException):
         self.teacher.find(
             By.XPATH,
             '//label[text()="%s"]' % assignment_title
         )
Example #26
0
 def test_user_select_course_by_appearance(self):
     """Select a course by its appearance."""
     self.user.login(self.server, self.login, self.password)
     courses = self.user.driver.find_elements(
         By.CLASS_NAME,
         'tutor-booksplash-course-item'
     )
     course_number = 0 if len(courses) <= 1 \
         else randint(1, len(courses)) - 1
     appearance = courses[course_number].get_attribute('data-appearance')
     appearance_courses = self.user.driver.find_elements(
             By.XPATH,
             '//div[contains(@data-appearance,"%s")]' % appearance
         )
     title = ''
     if isinstance(appearance_courses, list):
         for course in appearance_courses:
             title = title.join((' ', course.text))
     else:
         title = courses[course_number].text
     Assignment.scroll_to(self.user.driver, courses[course_number])
     self.user.select_course(appearance=appearance)
     was_successful = 'courses' in self.user.driver.current_url or \
         'list' in self.user.driver.current_url or \
         'calendar' in self.user.driver.current_url or \
         'contents' in self.user.driver.current_url
     assert(was_successful), \
         'Failed to select course in URL: %s' % self.user.driver.current_url
     if 'contents' in self.user.driver.current_url:
         return
     course_name = self.user.driver.find_element(
         By.CLASS_NAME,
         'course-name'
     ).text
     assert(course_name in title), \
         'Failed to select course "%s"' % course_name
Example #27
0
 def test_add_reading_assignment_one_cancel_305(self):
     """Build reading assignments."""
     # Reading, one period, cancel
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     left_delta = randint(0, 20)
     left = datetime.date.today() + datetime.timedelta(left_delta)
     start_date_1 = self.teacher.date_string(day_delta=left_delta)
     if not self.teacher.date_is_valid(left):
         start_date_1 = \
             (self.class_start_end_dates[0]) \
             .strftime('%m/%d/%Y')
     right_delta = left_delta + randint(1, 10)
     right = datetime.date.today() + datetime.timedelta(right_delta)
     end_date_1 = self.teacher.date_string(day_delta=right_delta)
     if not self.teacher.date_is_valid(right):
         end_date_1 = \
             (self.class_start_end_dates[1] - datetime.timedelta(2)) \
             .strftime('%m/%d/%Y')
     print('Left: %s  Right: %s' % (left, right))
     # self.book_sections = self.teacher.get_book_sections()
     reading_start = randint(0, (len(self.book_sections) - 1))
     reading_end = reading_start + randint(1, 5)
     reading_list = self.book_sections[reading_start:reading_end]
     sections = self.teacher.get_course_sections()
     if not isinstance(sections, list):
         sections = [sections]
     self.teacher.add_assignment(assignment='reading',
                                 args={
                                     'title': assignment_title,
                                     'description':
                                     'Staxing test reading - cancel',
                                     'periods': {
                                         sections[0]:
                                         (start_date_1, end_date_1),
                                     },
                                     'reading_list': reading_list,
                                     'status': 'cancel',
                                     'break_point': None,
                                 })
     assert('course' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date_1)
     time.sleep(5.0)
     with pytest.raises(NoSuchElementException):
         self.teacher.find(By.XPATH,
                           '//label[text()="%s"]' % assignment_title)
Example #28
0
 def test_add_reading_assignment_individual_publish(self):
     """Build reading assignments."""
     # Reading, individual periods, publish
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     left = randint(5, 20)
     right = left + randint(1, 10)
     start_date_1 = self.teacher.date_string(day_delta=left)
     end_date_1 = self.teacher.date_string(day_delta=left + right)
     start_date_2 = self.teacher.date_string(day_delta=left + 1)
     end_date_2 = self.teacher.date_string(day_delta=left + right + 1)
     start_time_2 = '6:30 am'
     end_time_2 = '11:59 pm'
     start_date_3 = self.teacher.date_string(day_delta=left + 2)
     end_date_3 = self.teacher.date_string(day_delta=left + right + 2)
     reading_options = self.teacher.get_book_sections()
     reading_start = randint(0, (len(reading_options) - 1))
     reading_end = reading_start + randint(1, 5)
     reading_list = reading_options[reading_start:reading_end]
     self.teacher.add_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'description': 'Staxing test reading - individual periods - ' +
                            'publish',
             'periods': {
                 'First': (start_date_1, end_date_1),
                 'Second': ((start_date_2, start_time_2),
                            (end_date_2, end_time_2)),
                 'Third': (start_date_3, end_date_3),
             },
             'reading_list': reading_list,
             'status': 'publish',
             'break_point': None,
         }
     )
     assert('courses' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date_1)
     reading = self.teacher.find(
         By.XPATH,
         '//label[text()="%s"]' % assignment_title
     )
     time.sleep(5.0)
     assert(reading), '%s not publishing on %s' % (assignment_title,
                                                   end_date_3)
    def test_student_select_an_exercise_answer_7691(self):
        """Select an exercise answer."""
        self.ps.test_updates['name'] = 'cc1.08.001' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = [
            'cc1',
            'cc1.08',
            'cc1.08.001',
            '7691'
        ]
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.get(self.book_url)
        self.student.sleep(2)
        self.student.find_all(By.XPATH, '//a[@class="nav next"]')[0].click()
        self.student.page.wait_for_page_load()
        try:
            widget = self.student.find(By.ID, 'coach-wrapper')
        except:
            self.student.find_all(By.XPATH,
                                  '//a[@class="nav next"]')[0].click()
            self.student.page.wait_for_page_load()
            try:
                self.student.sleep(1)
                widget = self.student.find(By.ID, 'coach-wrapper')
            except:
                self.student.find_all(By.XPATH,
                                      '//a[@class="nav next"]')[0].click()
                self.student.page.wait_for_page_load()
                self.student.sleep(1)
                widget = self.student.find(By.ID, 'coach-wrapper')
        Assignment.scroll_to(self.student.driver, widget)
        self.student.find(
            By.XPATH,
            '//button[span[contains(text(),"Launch Concept Coach")]]'
        ).click()
        self.student.sleep(1.5)
        base_window = self.student.driver.window_handles[0]
        self.student.find(By.CSS_SELECTOR, 'div.sign-up').click()
        self.student.sleep(3)
        popup = self.student.driver.window_handles[1]
        self.student.driver.switch_to_window(popup)
        self.student.find(By.LINK_TEXT, 'Sign up').click()
        self.student.find(By.ID, 'identity-login-button').click()
        self.student.find(
            By.ID,
            'signup_first_name'
        ).send_keys(self.first_name)
        self.student.find(By.ID, 'signup_last_name').send_keys(self.last_name)
        self.student.find(By.ID, 'signup_email_address').send_keys(self.email)
        self.student.find(By.ID, 'signup_username').send_keys(self.last_name)
        self.student.find(
            By.ID,
            'signup_password'
        ).send_keys(self.student.password)
        self.student.find(
            By.ID,
            'signup_password_confirmation'
        ).send_keys(self.student.password)
        self.student.find(By.ID, 'create_account_submit').click()
        self.student.find(By.ID, 'i_agree').click()
        self.student.find(By.ID, 'agreement_submit').click()
        self.student.find(By.ID, 'i_agree').click()
        self.student.find(By.ID, 'agreement_submit').click()
        self.student.driver.switch_to_window(base_window)
        self.student.find(
            By.XPATH,
            '//input[contains(@label,"Enter the enrollment code")]'
        ).send_keys(self.code)
        self.student.sleep(2)
        self.student.find(By.CSS_SELECTOR, 'button.enroll').click()
        self.student.sleep(2)
        self.student.find(
            By.CSS_SELECTOR,
            'div.field input.form-control'
        ).send_keys(self.last_name)
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.sleep(5)
        try:
            self.student.find(By.XPATH, '//button[text()="Continue"]').click()
        except:
            print('Two-step message not seen.')
        self.student.wait.until(
            expect.element_to_be_clickable(
                (By.XPATH,
                 '//div[@class="openstax-question"]//textarea')
            )
        ).send_keys(chomsky())
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//div[@class="answer-letter"]')
            )
        )
        answers = self.student.find_all(By.CSS_SELECTOR, 'div.answer-letter')
        answers[randint(0, len(answers) - 1)].click()
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()

        self.ps.test_updates['passed'] = True
    def test_student_completion_report_shows_the_section_status_of_7733(self):
        """Completion report shows the section status.

        Steps:
        Click on "Contents"
        Select a section
        Scroll to bottom of the section
        Click "Launch Concept Coach"
        Enter a response into the free response text box
        Click "Answer"
        Select a multiple choice answer
        Click "Submit"
        Click "Next question"
        Continue answering questions

        Expected Result:
        The user is presented with the completion report, which shows the
        section status of completed modules
        """
        self.ps.test_updates['name'] = 'cc1.09.002' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc1', 'cc1.09', 'cc1.09.002', '7733']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.find(By.CSS_SELECTOR, 'div.media-nav button').click()
        self.student.sleep(1)
        self.student.find(By.XPATH, '//a[span[text()="1.2"]]').click()
        self.student.sleep(1)
        self.student.find(By.CSS_SELECTOR, 'div.jump-to-cc a').click()
        self.student.sleep(0.5)
        self.student.find(By.CSS_SELECTOR,
                          'div.concept-coach-launcher button').click()
        try:
            self.student.find(By.XPATH, '//button[text()="Continue"]').click()
        except:
            print('Two-step message not seen.')

        # Go to the first question
        ids = 0
        self.student.find(By.XPATH,
                          "//div[@class='task-breadcrumbs']/span").click()

        # Work through Concept Coach
        page = self.student.driver.page_source
        while 'or review your work below.' not in page:
            self.student.find(
                By.XPATH, "//span[@class='exercise-identifier-link']/span[2]")
            ids += 1

            action = False
            # Free response
            try:
                self.student.find(By.TAG, 'textarea').send_keys(chomsky())
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            # Multiple choice
            try:
                answers = self.student.find_all(By.CSS_SELECTOR,
                                                'div.answer-letter')
                if not isinstance(answers, list):
                    Assignment.scroll_to(self.student.driver, answers)
                    answers.click()
                else:
                    Assignment.scroll_to(self.student.driver, answers[0])
                    answers[randint(0, len(answers) - 1)].click()
                self.student.sleep(0.2)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            self.student.sleep(2)
            page = self.student.driver.page_source
        self.student.sleep(5)

        section_id = self.student.find(
            By.CSS_SELECTOR,
            'h3.chapter-section-prefix').get_attribute('data-section')
        problem_id = self.student.find(
            By.XPATH, '//span[contains(@data-reactid,"help-links.1")]').text

        assert(section_id == problem_id), \
            'Section ID does not match the problem ID'

        self.ps.test_updates['passed'] = True
    def test_student_view_section_completion_report_7732(self):
        """View section completion report.

        Steps:
        Go to Tutor
        Click on the 'Login' button
        Enter the student user account in the username and password text boxes
        Click on the 'Sign in' button
        If the user has more than one course, click on a CC course name
        Click on "Contents"
        Select a section
        Scroll to bottom of the section
        Click "Launch Concept Coach"
        Enter a response into the free response text box
        Click "Answer"
        Select a multiple choice answer
        Click "Submit"
        Click "Next question"
        Continue answering questions

        Expected Result:
        The user is presented with section completion report
        that shows "You're done"
        """
        self.ps.test_updates['name'] = 'cc1.09.001' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc1', 'cc1.09', 'cc1.09.001', '7732']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.sleep(5)
        self.student.find(By.XPATH, "//button[@class='toggle btn']").click()
        self.student.sleep(3)
        self.student.find(
            By.XPATH,
            "//div/ul/li[2]/ul/li[2]/div/span[@class='name-wrapper']" +
            "/a/span[@class='title']").click()
        self.student.sleep(1)
        self.student.find(
            By.XPATH, "//div[@class='jump-to-cc']/a[@class='btn']").click()
        self.student.sleep(1)
        self.student.find(By.XPATH,
                          "//button[@class='btn btn-lg btn-primary']").click()

        self.student.sleep(5)
        page = self.student.driver.page_source

        # Work through Concept Coach
        while 'or review your work below.' not in page:
            # Free response
            try:
                self.student.find(By.TAG, 'textarea').send_keys(chomsky())
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            # Multiple choice
            try:
                answers = self.student.find_all(By.CSS_SELECTOR,
                                                'div.answer-letter')
                if not isinstance(answers, list):
                    Assignment.scroll_to(self.student.driver, answers)
                    answers.click()
                else:
                    Assignment.scroll_to(self.student.driver, answers[0])
                    answers[randint(0, len(answers) - 1)].click()
                self.student.sleep(0.2)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            self.student.sleep(2)
            page = self.student.driver.page_source

        self.ps.test_updates['passed'] = True
    def test_teacher_change_a_draft_event_162184(self):
        self.ps.test_updates['name'] = 'tutor_event_teacher' \
                                       + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['tutor', 'event', 'teacher',
                                        '162184']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        assignment_name = 'event_013_%s' % randint(100, 500)
        assignment = Assignment()
        today = datetime.date.today()
        finish = randint(1, 5)
        begin = today.strftime('%m/%d/%Y')
        end = (today + datetime.timedelta(days=finish)) \
            .strftime('%m/%d/%Y')

        # Create a draft assignment
        self.teacher.add_assignment(
            assignment='event',
            args={
                'title': assignment_name,
                'description': 'description',
                'periods': {'all': (begin, end)},
                'status': 'draft',
            }
        )

        # Find the draft Event on the calendar
        self.teacher.wait.until(
            expect.presence_of_element_located(
                (By.CLASS_NAME, 'month-wrapper')
            )
        )
        self.teacher.find(
            By.XPATH,
            '//label[contains(text(),"{0}")]'.format(assignment_name)
        ).click()
        sleep(1)

        # Change the title
        self.teacher.find(
            By.ID, "reading-title"
        ).send_keys("changed")

        # Change the description
        self.teacher.find(
            By.CSS_SELECTOR, ".assignment-description>.form-control"
        ).send_keys("changed")

        # Set new due dates
        today = datetime.date.today()
        start = randint(1, 6)
        end = start + randint(1, 5)
        opens_on = (today + datetime.timedelta(days=start)) \
            .strftime('%m/%d/%Y')
        closes_on = (today + datetime.timedelta(days=end)) \
            .strftime('%m/%d/%Y')
        assignment.assign_periods(
            self.teacher.driver,
            {'all': (opens_on, closes_on)}
        )

        # Save as draft
        self.teacher.find(
            By.XPATH, '//button[contains(@class,"-save")]'
        ).click()
        sleep(1)

        # Find the new title on the calendar
        try:
            self.teacher.find(
                By.XPATH,
                '//label[contains(text(),"{0}")]'.format(
                    assignment_name + 'changed')
            )
        except NoSuchElementException:
            self.teacher.find(
                By.XPATH,
                '//a[contains(@class,"header-control next")]'
            ).click()
            self.teacher.find(
                By.XPATH,
                '//label[contains(text(),"{0}")]'.format(
                    assignment_name + 'changed')
            )

        self.ps.test_updates['passed'] = True
    def test_student_select_an_exercise_answer_7691(self):
        """Select an exercise answer."""
        self.ps.test_updates['name'] = 'cc1.08.001' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc1', 'cc1.08', 'cc1.08.001', '7691']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.get(self.book_url)
        self.student.sleep(2)
        self.student.find_all(By.XPATH, '//a[@class="nav next"]')[0].click()
        self.student.page.wait_for_page_load()
        try:
            widget = self.student.find(By.ID, 'coach-wrapper')
        except:
            self.student.find_all(By.XPATH,
                                  '//a[@class="nav next"]')[0].click()
            self.student.page.wait_for_page_load()
            try:
                self.student.sleep(1)
                widget = self.student.find(By.ID, 'coach-wrapper')
            except:
                self.student.find_all(By.XPATH,
                                      '//a[@class="nav next"]')[0].click()
                self.student.page.wait_for_page_load()
                self.student.sleep(1)
                widget = self.student.find(By.ID, 'coach-wrapper')
        Assignment.scroll_to(self.student.driver, widget)
        self.student.find(
            By.XPATH,
            '//button[span[contains(text(),"Launch Concept Coach")]]').click()
        self.student.sleep(1.5)
        base_window = self.student.driver.window_handles[0]
        self.student.find(By.CSS_SELECTOR, 'div.sign-up').click()
        self.student.sleep(3)
        popup = self.student.driver.window_handles[1]
        self.student.driver.switch_to_window(popup)
        self.student.find(By.LINK_TEXT, 'Sign up').click()
        self.student.find(By.ID, 'identity-login-button').click()
        self.student.find(By.ID,
                          'signup_first_name').send_keys(self.first_name)
        self.student.find(By.ID, 'signup_last_name').send_keys(self.last_name)
        self.student.find(By.ID, 'signup_email_address').send_keys(self.email)
        self.student.find(By.ID, 'signup_username').send_keys(self.last_name)
        self.student.find(By.ID,
                          'signup_password').send_keys(self.student.password)
        self.student.find(By.ID, 'signup_password_confirmation').send_keys(
            self.student.password)
        self.student.find(By.ID, 'create_account_submit').click()
        self.student.find(By.ID, 'i_agree').click()
        self.student.find(By.ID, 'agreement_submit').click()
        self.student.find(By.ID, 'i_agree').click()
        self.student.find(By.ID, 'agreement_submit').click()
        self.student.driver.switch_to_window(base_window)
        self.student.find(
            By.XPATH,
            '//input[contains(@label,"Enter the enrollment code")]').send_keys(
                self.code)
        self.student.sleep(2)
        self.student.find(By.CSS_SELECTOR, 'button.enroll').click()
        self.student.sleep(2)
        self.student.find(By.CSS_SELECTOR,
                          'div.field input.form-control').send_keys(
                              self.last_name)
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.sleep(5)
        try:
            self.student.find(By.XPATH, '//button[text()="Continue"]').click()
        except:
            print('Two-step message not seen.')
        self.student.wait.until(
            expect.element_to_be_clickable(
                (By.XPATH,
                 '//div[@class="openstax-question"]//textarea'))).send_keys(
                     chomsky())
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//div[@class="answer-letter"]')))
        answers = self.student.find_all(By.CSS_SELECTOR, 'div.answer-letter')
        answers[randint(0, len(answers) - 1)].click()
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()
        self.student.find(By.CSS_SELECTOR, 'button.async-button').click()

        self.ps.test_updates['passed'] = True
Example #34
0
    def test_add_reading_assignment_individual_publish_301(self):
        """Build reading assignments.

        Type:     reading
        Sections: individualized
        Action:   publish
        """
        assignment_title = 'Reading-%s' % Assignment.rword(5)

        left_delta = randint(0, 20)
        left = datetime.date.today() + datetime.timedelta(left_delta)
        start_date_1 = self.teacher.date_string(day_delta=left_delta)
        start_date_2 = self.teacher.date_string(day_delta=left_delta + 1)
        start_date_3 = self.teacher.date_string(day_delta=left_delta + 2)
        start_date_4 = self.teacher.date_string(day_delta=left_delta + 3)
        if not self.teacher.date_is_valid(left):
            start_date_1 = (self.class_start_end_dates[0]) \
                .strftime('%m/%d/%Y')
            start_date_2 = \
                (self.class_start_end_dates[0] + datetime.timedelta(1)) \
                .strftime('%m/%d/%Y')
            start_date_3 = \
                (self.class_start_end_dates[0] + datetime.timedelta(2)) \
                .strftime('%m/%d/%Y')
            start_date_4 = \
                (self.class_start_end_dates[0] + datetime.timedelta(3)) \
                .strftime('%m/%d/%Y')
        right_delta = left_delta + randint(1, 10)
        right = datetime.date.today() + datetime.timedelta(right_delta)
        end_date_1 = self.teacher.date_string(day_delta=right_delta)
        end_date_2 = self.teacher.date_string(day_delta=right_delta + 1)
        end_date_3 = self.teacher.date_string(day_delta=right_delta + 2)
        end_date_4 = self.teacher.date_string(day_delta=right_delta + 3)
        if not self.teacher.date_is_valid(right):
            end_date_1 = \
                (self.class_start_end_dates[1] - datetime.timedelta(3)) \
                .strftime('%m/%d/%Y')
            end_date_2 = \
                (self.class_start_end_dates[1] - datetime.timedelta(2)) \
                .strftime('%m/%d/%Y')
            end_date_3 = \
                (self.class_start_end_dates[1] - datetime.timedelta(1)) \
                .strftime('%m/%d/%Y')
            end_date_4 = \
                (self.class_start_end_dates[1]) \
                .strftime('%m/%d/%Y')
        print('Left: %s  Right: %s' % (left, right))
        start_time_2 = '6:30 am'
        end_time_2 = '11:59 pm'
        reading_start = randint(0, (len(self.book_sections) - 1))
        reading_end = reading_start + randint(1, 5)
        reading_list = self.book_sections[reading_start:reading_end]
        sections = self.teacher.get_course_sections()
        assign_sections = {}
        if len(sections) >= 1 and sections[0]:
            assign_sections[sections[0]] = (start_date_1, end_date_1)
        if len(sections) >= 2 and sections[1]:
            assign_sections[sections[1]] = ((start_date_2, start_time_2),
                                            (end_date_2, end_time_2))
        if len(sections) >= 3 and sections[2]:
            assign_sections[sections[2]] = (start_date_3, end_date_3)
        if len(sections) >= 4 and sections[3]:
            assign_sections[sections[3]] = (start_date_4, end_date_4)
        for number, section in enumerate(sections):
            assign_sections[section] = ((start_date_1, start_time_2),
                                        (end_date_1, end_time_2))
        self.teacher.add_assignment(
            assignment='reading',
            args={
                'title': assignment_title,
                'description':
                'Staxing test reading - individual periods - ' + 'publish',
                'periods': assign_sections,
                'reading_list': reading_list,
                'status': 'publish',
                'break_point': None,
            })
        assert('course' in self.teacher.current_url()), \
            'Not at dashboard'
        print(self.teacher.current_url())
        self.teacher.rotate_calendar(end_date_1)
        reading = self.teacher.find(By.XPATH,
                                    '//label[text()="%s"]' % assignment_title)
        time.sleep(5.0)
        assert (reading), '%s not publishing on %s' % (assignment_title,
                                                       end_date_1)
    def test_student_display_the_assignment_summary_after_completin_7697(self):
        """Display the assignment summary after completing the assignment.

        Steps:
        Go to Tutor
        Click on the 'Login' button
        Enter the student user account in the username and password text boxes
        Click on the 'Sign in' button
        If the user has more than one course, click on a CC course name
        Click the 'Contents' button to open the table of contents
        Click on a chapter
        Click on a non-introductory section
        Click the 'Launch Concept Coach' button at the bottom of the page
        Type text into the 'Enter your response' text box
        Click a multiple choice answer
        Click the 'Submit' button
        After answering the last question, click the 'Next Question' button

        Expected Result:
        The summary is displayed
        """
        self.ps.test_updates['name'] = 'cc1.08.007' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc1', 'cc1.08', 'cc1.08.007', '7697']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.select_course(appearance='macro_economics')
        self.student.sleep(5)
        self.student.find(By.XPATH, "//button[@class='toggle btn']").click()
        self.student.sleep(3)

        finished = False

        # Expand all the chapters in the table of contents
        chapters = self.student.driver.find_elements_by_xpath(
            "//span[@class='title section']")
        chapters.pop(0)
        for chapter in chapters:
            chapter.click()

        # Get all sections, excluding the preface
        sections = self.student.driver.find_elements_by_xpath(
            "//a/span[@class='title']")
        sections.pop(0)

        self.student.sleep(2)

        length = len(sections)

        for num in range(length):

            sections = self.student.driver.find_elements_by_xpath(
                "//a/span[@class='title']")
            sections.pop(0)
            sections[num].click()
            self.student.sleep(3)

            if 'Introduction-to' not in self.student.current_url():
                # Jump to the Concept Coach widget and open Concept Coach
                self.student.find(
                    By.XPATH,
                    "//div[@class='jump-to-cc']/a[@class='btn']").click()
                self.student.sleep(2)
                self.student.find(
                    By.XPATH,
                    "//button[@class='btn btn-lg btn-primary']").click()
                self.student.sleep(2)

                # If this section has been completed already,
                # leave and go to the next section
                breadcrumbs = self.student.driver.find_elements_by_xpath(
                    "//div[@class='task-breadcrumbs']/span")

                breadcrumbs[-1].click()
                self.student.sleep(3)

                if len(
                        self.student.driver.find_elements_by_xpath(
                            "//div[@class='card-body coach-coach-review-completed'][1]"
                        )) > 0:
                    self.student.find(
                        By.XPATH, "//a/button[@class='btn-plain " +
                        "-coach-close btn btn-default']").click()

                # Else, go through questions until a blank one is found
                # and answer the question
                else:
                    for question in breadcrumbs:
                        question.click()

                        if len(
                                self.student.driver.find_elements_by_xpath(
                                    "//div[@class='question-feedback bottom']")
                        ) > 0:
                            if len(
                                    self.student.driver.find_elements_by_xpath(
                                        "//div[@class='card-body coach-" +
                                        "coach-review-completed'][1]")) > 0:
                                finished = True
                            continue

                        else:
                            while len(
                                    self.student.driver.find_elements_by_xpath(
                                        "//div[@class='question-feedback bottom']"
                                    )) == 0:
                                # Free response

                                if len(
                                        self.student.driver.
                                        find_elements_by_xpath(
                                            "//button[@class='btn btn-default']"
                                        )) > 0:
                                    self.student.find(
                                        By.XPATH,
                                        "//button[@class='btn btn-default']"
                                    ).click()
                                    continue

                                if self.student.find(
                                        By.XPATH,
                                        "//button[@class='async-button " +
                                        "continue btn btn-primary']"
                                ).text == 'Answer':
                                    self.student.find(
                                        By.XPATH, "//textarea").send_keys(
                                            'An answer for this textarea')
                                    self.student.find(
                                        By.XPATH,
                                        "//button[@class='async-button " +
                                        "continue btn btn-primary']").click()
                                    self.student.sleep(3)

                                # Multiple Choice
                                elif self.student.find(
                                        By.XPATH,
                                        "//button[@class='async-button " +
                                        "continue btn btn-primary']"
                                ).text == 'Submit':
                                    answers = self.student.driver.find_elements(  # NOQA
                                        By.CLASS_NAME, 'answer-letter')
                                    self.student.sleep(0.8)
                                    rand = randint(0, len(answers) - 1)
                                    answer = chr(ord('a') + rand)
                                    Assignment.scroll_to(
                                        self.student.driver, answers[0])
                                    if answer == 'a':
                                        self.student.driver.execute_script(
                                            'window.scrollBy(0, -160);')
                                    elif answer == 'd':
                                        self.student.driver.execute_script(
                                            'window.scrollBy(0, 160);')
                                    answers[rand].click()

                                    self.student.find(
                                        By.XPATH,
                                        "//button[@class='async-button " +
                                        "continue btn btn-primary']").click()
                                    self.student.sleep(3)

            if finished:
                break

        self.student.sleep(5)

        self.ps.test_updates['passed'] = True
Example #36
0
 def scroll_to(self, location):
     Assignment.scroll_to(self.driver, location)
     return self
Example #37
0
 def test_add_reading_assignment_individual_draft_303(self):
     """Build reading assignments."""
     # Reading, individual periods, draft
     assignment_title = 'Reading-%s' % Assignment.rword(5)
     left_delta = randint(0, 20)
     left = datetime.date.today() + datetime.timedelta(left_delta)
     '''start_date_1 = self.teacher.date_string(day_delta=left_delta)
     start_date_2 = self.teacher.date_string(day_delta=left_delta + 1)
     start_date_3 = self.teacher.date_string(day_delta=left_delta + 2)
     if not self.teacher.date_is_valid(left):
         start_date_1 = \
             (self.class_start_end_dates[0]).strftime('%m/%d/%Y')
         start_date_2 = \
             (self.class_start_end_dates[0] + datetime.timedelta(1)) \
             .strftime('%m/%d/%Y')
         start_date_3 = \
             (self.class_start_end_dates[0] + datetime.timedelta(2)) \
             .strftime('%m/%d/%Y')'''
     right_delta = left_delta + randint(1, 10)
     right = datetime.date.today() + datetime.timedelta(right_delta)
     end_date_1 = self.teacher.date_string(day_delta=right_delta)
     # end_date_2 = self.teacher.date_string(day_delta=right_delta + 1)
     end_date_3 = self.teacher.date_string(day_delta=right_delta + 2)
     if not self.teacher.date_is_valid(right):
         end_date_1 = \
             (self.class_start_end_dates[1] - datetime.timedelta(2)) \
             .strftime('%m/%d/%Y')
         # end_date_2 = \
         #     (self.class_start_end_dates[1] - datetime.timedelta(1)) \
         #     .strftime('%m/%d/%Y')
         end_date_3 = \
             (self.class_start_end_dates[1]) \
             .strftime('%m/%d/%Y')
     print('Left: %s  Right: %s' % (left, right))
     # self.book_sections = self.teacher.get_book_sections()
     reading_start = randint(0, (len(self.book_sections) - 1))
     reading_end = reading_start + randint(1, 5)
     reading_list = self.book_sections[reading_start:reading_end]
     sections = self.teacher.get_course_sections()
     periods = {}
     for index, section in enumerate(sections):
         periods[section] = \
             (self.teacher.date_string(day_delta=left_delta + index),
              self.teacher.date_string(day_delta=right_delta + index))
     self.teacher.add_assignment(
         assignment='reading',
         args={
             'title': assignment_title,
             'description':
             'Staxing test reading - individual periods ' + '- draft',
             'periods': periods,
             'reading_list': reading_list,
             'status': 'draft',
             'break_point': None,
         })
     assert('course' in self.teacher.current_url()), \
         'Not at dashboard'
     self.teacher.rotate_calendar(end_date_1)
     reading = self.teacher.find(By.XPATH,
                                 '//label[text()="%s"]' % assignment_title)
     time.sleep(5.0)
     assert (reading), '%s not publishing on %s' % (assignment_title,
                                                    end_date_3)
Example #38
0
 def date_string(self, day_delta=0, str_format='%m/%d/%Y'):
     """System date format pass-through."""
     return Assignment().to_date_string(day_delta, str_format)
    def test_student_completion_report_shows_the_section_status_of_7733(self):
        """Completion report shows the section status.

        Steps:
        Click on "Contents"
        Select a section
        Scroll to bottom of the section
        Click "Launch Concept Coach"
        Enter a response into the free response text box
        Click "Answer"
        Select a multiple choice answer
        Click "Submit"
        Click "Next question"
        Continue answering questions

        Expected Result:
        The user is presented with the completion report, which shows the
        section status of completed modules
        """
        self.ps.test_updates['name'] = 'cc1.09.002' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = [
            'cc1',
            'cc1.09',
            'cc1.09.002',
            '7733'
        ]
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.find(By.CSS_SELECTOR, 'div.media-nav button').click()
        self.student.sleep(1)
        self.student.find(By.XPATH, '//a[span[text()="1.2"]]').click()
        self.student.sleep(1)
        self.student.find(By.CSS_SELECTOR, 'div.jump-to-cc a').click()
        self.student.sleep(0.5)
        self.student.find(
            By.CSS_SELECTOR,
            'div.concept-coach-launcher button'
        ).click()
        try:
            self.student.find(By.XPATH, '//button[text()="Continue"]').click()
        except:
            print('Two-step message not seen.')

        # Work through Concept Coach
        page = self.student.driver.page_source
        while 'or review your work below.' not in page:
            # Free response
            try:
                self.student.find(By.TAG, 'textarea').send_keys(chomsky())
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            # Multiple choice
            try:
                answers = self.student.find_all(By.CSS_SELECTOR,
                                                'div.answer-letter')
                if not isinstance(answers, list):
                    Assignment.scroll_to(self.student.driver, answers)
                    answers.click()
                else:
                    Assignment.scroll_to(self.student.driver, answers[0])
                    answers[randint(0, len(answers) - 1)].click()
                self.student.sleep(0.2)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            self.student.sleep(2)
            page = self.student.driver.page_source
        self.student.sleep(5)

        section_id = self.student.find(
            By.CSS_SELECTOR,
            'h3.chapter-section-prefix'
        ).get_attribute('data-section')
        problem_id = self.student.find(
            By.XPATH,
            '//span[contains(@data-reactid,"help-links.1")]'
        ).text

        assert(section_id == problem_id), \
            'Section ID does not match the problem ID'

        self.ps.test_updates['passed'] = True
    def test_teacher_exclude_certain_questions_14852(self):
        """Exclude certain quesitons.

        Steps:
        If the user has more than one course, click on a CC course name
        Click "Question Library" from the user menu
        Select a section or chapter
        Click "Show Questions"
        Hover over the desired question and click "Exclude question"

        Expected Result:
        Question is grayed out
        """
        self.ps.test_updates['name'] = 'cc2.11.002' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc2', 'cc2.11', 'cc2.11.002', '14852']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.teacher.login()
        self.teacher.find(
            By.XPATH, '//a[contains(@href,"/cc-dashboard")]'
        ).click()
        self.teacher.open_user_menu()
        self.teacher.find(
            By.LINK_TEXT, 'Question Library'
        ).click()
        self.teacher.find(
            By.XPATH,
            '//div[@class="section"]//span[@class="chapter-section" ' +
            'and @data-chapter-section="1.2"]'
        ).click()
        self.teacher.driver.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")
        self.teacher.find(
            By.XPATH, '//button[text()="Show Questions"]'
        ).click()
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//div[@class="exercises"]')
            )
        )
        self.teacher.sleep(1)
        i = 1
        question = None
        # loop finding a question that is not yet excleded
        # there are 9 question in the exact textbook and chpater this test
        # is searching. limiting loop at 7 incase questions are removed.
        while i < 8:
            question = self.teacher.find(
                By.XPATH,
                '//div[@class="exercises"]/div[' + str(i) + ']'
            )
            if ('is-selected' not in question.get_attribute('class')):
                break
            i += 1
        Assignment.scroll_to(self.teacher.driver, question)
        self.teacher.sleep(1)
        actions = ActionChains(self.teacher.driver)
        actions.move_to_element(question)
        # way to stall because not sure how to add wait in action chain
        for _ in range(50):
            actions.move_by_offset(-1, 0)
        actions.click()
        actions.move_by_offset(-50, -300)
        actions.perform()
        self.teacher.sleep(0.5)
        question_excluded = self.teacher.find(
            By.XPATH, '//div[@class="exercises"]/div[' + str(i) + ']'
        ).get_attribute('class')
        assert('is-selected' in question_excluded), 'question not excluded'
        self.ps.test_updates['passed'] = True
Example #41
0
 def test_assignment_class_method_rword(self):
     """Test the random character string generator."""
     x_05 = Assignment.rword(5)
     x_15 = Assignment.rword(15)
     assert (len(x_05) == 5 and len(x_15) == 15), 'Incorrect string length'
     assert (Assignment.rword(0) == ''), 'Non-empty string returned'
Example #42
0
class TestStaxingAssignment(unittest.TestCase):
    """Staxing case tests for Assignment."""
    def setUp(self):
        """Pretest settings."""
        self.assignment = Assignment()
        option_set = options.Options()
        option_set.add_argument('disable-infobars')
        option_set.add_argument('enable-devtools-experiments')
        option_set.add_argument('disable-search-geolocation-disclosure')
        if 'headless' in DRIVER:
            option_set.add_argument('headless')
        option_set.add_experimental_option(
            'prefs', {
                'credentials_enable_service': False,
                'profile': {
                    'password_manager_enabled': False
                }
            })
        if 'chrome' in DRIVER or 'headless' in DRIVER:
            self.driver = webdriver.Chrome(chrome_options=option_set)
        self.wait = WebDriverWait(self.driver, 15)
        self.driver.implicitly_wait(1)

    def tearDown(self):
        """Test destructor."""
        try:
            self.assignment.__del__()
        except Exception:
            pass
        try:
            self.driver.__del__()
        except Exception:
            pass

    def setup_user_and_dates(self):
        user = User(username=os.getenv('TEACHER_USER'),
                    password=os.getenv('TEACHER_PASSWORD'),
                    existing_driver=self.driver)
        user.login()
        user.select_course(appearance='biology')

        today = datetime.date.today()
        open_on = (today + datetime.timedelta(days=3)).strftime('%m/%d/%Y')
        due_at = (today + datetime.timedelta(days=6)).strftime('%m/%d/%Y')
        return (user, open_on, due_at)

    def test_assignment_class_method_rword(self):
        """Test the random character string generator."""
        x_05 = Assignment.rword(5)
        x_15 = Assignment.rword(15)
        assert (len(x_05) == 5 and len(x_15) == 15), 'Incorrect string length'
        assert (Assignment.rword(0) == ''), 'Non-empty string returned'

    def test_assignment_class_method_scroll_to(self):
        """Test page scrolling to show aspecific element."""
        self.driver.set_window_size(1024, 768)
        self.driver.get('https://www.google.com/#q=openstax')
        time.sleep(1)
        last_link = self.driver.find_elements(By.CSS_SELECTOR, 'div.g')
        assert (last_link), 'No elements found'
        last_link = last_link[-2].find_element(By.TAG_NAME, 'a')
        with self.assertRaises(WebDriverException):
            last_link.click()
        Assignment.scroll_to(self.driver, last_link, True)
        time.sleep(3)
        last_link.click()

    def test_assignment_class_method_send_keys(self):
        """Test send keystrokes individually."""
        self.driver.get('https://www.randomlists.com/random-words')
        self.driver.find_element(By.NAME, 'submit').click()
        word_list = self.driver.find_elements(By.CSS_SELECTOR, '.crux')
        word = word_list[randint(0, len(word_list) - 1)].text
        self.driver.get('https://duckduckgo.com/')
        search = self.driver.find_element(By.ID, 'search_form_input_homepage')
        Assignment.send_keys(self.driver, search, word + '\n')
        search = self.driver.find_element(By.ID, 'search_form_input')
        assert (word in self.driver.page_source.lower()), 'Word not searched'

    def test_assignment_open_assignment_menu(self):
        """Test opening the assignment creation menu."""
        self.driver.get('https://' + os.getenv('SERVER_URL'))
        self.driver.find_element(By.CSS_SELECTOR, '.login').click()
        login = self.driver.find_element(By.CSS_SELECTOR,
                                         '#login_username_or_email')
        login.click()
        login.send_keys(os.getenv('TEACHER_USER'))
        self.driver.find_element(By.CSS_SELECTOR, '[type=submit]').click()
        password = self.driver.find_element(By.CSS_SELECTOR, '#login_password')
        password.click()
        password.send_keys(os.getenv('TEACHER_PASSWORD'))
        self.driver.find_element(By.CSS_SELECTOR, '[type=submit]').click()
        courses = self.driver.find_elements(
            By.CSS_SELECTOR,
            '.my-courses-current [data-course-course-type=tutor]')
        courses[randint(0, len(courses) - 1)].click()
        try:
            self.wait.until(
                expect.element_to_be_clickable((
                    By.XPATH,
                    '//button[contains(text(),"For extra credit")]'))).click()
            self.find(By.CLASS_NAME, 'btn-primary').click()
        except Exception:
            pass
        menu = self.driver.find_element(By.CLASS_NAME, 'sidebar-toggle')
        Assignment.scroll_to(self.driver, menu)
        if 'open' not in menu.get_attribute('class'):
            time.sleep(2)
            menu.click()
        self.assignment.open_assignment_menu(self.driver)
        assert ('open' in menu.get_attribute('class'))

    def test_assignment_modify_time(self):
        """Test time modification."""
        assert ('400a' == self.assignment.modify_time('4:00 am'))
        assert ('800a' == self.assignment.modify_time('8:00a'))
        assert ('800p' == self.assignment.modify_time('800p'))
        assert ('800p' == self.assignment.modify_time('8:00 pm'))
        assert ('1000a' == self.assignment.modify_time('1000a'))
        assert ('1000p' == self.assignment.modify_time('1000p'))

    '''def test_assignment_adjust_date_picker(self):
        """
        Test the date picker rotation to move to the
        correct month and year.
        """

        pass

    def test_assignment_assign_time(self):
        """"""

    def test_assignment_to_date_string(self):
        """"""

    def test_assignment_assign_date(self):
        """"""

    def test_assignment_assign_periods(self):
        """"""

    def test_assignment_select_status(self):
        """"""

    def test_assignment_open_chapter_list(self):
        """"""

    def test_assignment_select_sections(self):
        """"""'''

    def test_assignment_add_new_reading(self):
        """Add a new reading."""
        user, _open, _due = self.setup_user_and_dates()
        self.assignment.add_new_reading(
            driver=self.driver,
            title='New-Reading',
            description='test_assignment_add_new_reading',
            periods={'all': (_open, _due)},
            readings=['ch5'],
            status='publish')

    '''def test_assignment_find_all_questions(self):
        """"""

    def test_assignment_get_chapter_list(self):
        """"""

    def test_assignment_set_tutor_selections(self):
        """"""

    def test_assignment_add_homework_problems(self):
        """"""'''

    def test_assignment_add_new_homework(self):
        """Add a new homework."""
        user, _open, _due = self.setup_user_and_dates()
        self.assignment.add_new_homework(
            driver=user.driver,
            title='NewReading',
            description='test_assignment_add_new_homework',
            periods={'all': (_open, _due)},
            problems={
                '1.1': 3,
                'tutor': 3
            },
            status='publish',
            feedback='immediate')

    def test_assignment_add_new_external(self):
        """Add a new external assignment."""
        user, _open, _due = self.setup_user_and_dates()
        self.assignment.add_new_external(
            driver=user.driver,
            title='New-External',
            description='test_assignment_add_new_external',
            periods={'all': (_open, _due)},
            assignment_url='google.com',
            status='publish')

    def test_assignment_add_new_event(self):
        """Add a new event."""
        user, _open, _due = self.setup_user_and_dates()
        self.assignment.add_new_event(
            driver=user.driver,
            title='New-Event',
            description='test_assignment_add_new_event',
            periods={'all': (_open, _due)},
            status='publish')

    '''def test_assignment_change_reading(self):
    def test_student_view_section_completion_report_7732(self):
        """View section completion report.

        Steps:
        Go to Tutor
        Click on the 'Login' button
        Enter the student user account in the username and password text boxes
        Click on the 'Sign in' button
        If the user has more than one course, click on a CC course name
        Click on "Contents"
        Select a section
        Scroll to bottom of the section
        Click "Launch Concept Coach"
        Enter a response into the free response text box
        Click "Answer"
        Select a multiple choice answer
        Click "Submit"
        Click "Next question"
        Continue answering questions

        Expected Result:
        The user is presented with section completion report
        that shows "You're done"
        """
        self.ps.test_updates['name'] = 'cc1.09.001' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = [
            'cc1',
            'cc1.09',
            'cc1.09.001',
            '7732'
        ]
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.student.sleep(5)
        self.student.find(By.XPATH, "//button[@class='toggle btn']").click()
        self.student.sleep(3)
        self.student.find(
            By.XPATH,
            "//div/ul/li[2]/ul/li[2]/div/span[@class='name-wrapper']" +
            "/a/span[@class='title']").click()
        self.student.sleep(1)
        self.student.find(
            By.XPATH, "//div[@class='jump-to-cc']/a[@class='btn']").click()
        self.student.sleep(1)
        self.student.find(
            By.XPATH, "//button[@class='btn btn-lg btn-primary']").click()

        self.student.sleep(5)
        page = self.student.driver.page_source

        # Work through Concept Coach
        while 'or review your work below.' not in page:
            # Free response
            try:
                self.student.find(By.TAG, 'textarea').send_keys(chomsky())
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            # Multiple choice
            try:
                answers = self.student.find_all(By.CSS_SELECTOR,
                                                'div.answer-letter')
                if not isinstance(answers, list):
                    Assignment.scroll_to(self.student.driver, answers)
                    answers.click()
                else:
                    Assignment.scroll_to(self.student.driver, answers[0])
                    answers[randint(0, len(answers) - 1)].click()
                self.student.sleep(0.2)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
                self.student.find(By.CSS_SELECTOR, 'button.continue').click()
                self.student.sleep(0.3)
            except:
                pass
            self.student.sleep(2)
            page = self.student.driver.page_source

        self.ps.test_updates['passed'] = True
Example #44
0
    def test_teacher_exclude_certain_questions_14852(self):
        """Exclude certain quesitons.

        Steps:
        If the user has more than one course, click on a CC course name
        Click "Question Library" from the user menu
        Select a section or chapter
        Click "Show Questions"
        Hover over the desired question and click "Exclude question"

        Expected Result:
        Question is grayed out
        """
        self.ps.test_updates['name'] = 'cc2.11.002' \
            + inspect.currentframe().f_code.co_name[4:]
        self.ps.test_updates['tags'] = ['cc2', 'cc2.11', 'cc2.11.002', '14852']
        self.ps.test_updates['passed'] = False

        # Test steps and verification assertions
        self.teacher.login()
        self.teacher.find(By.XPATH,
                          '//a[contains(@href,"/cc-dashboard")]').click()
        self.teacher.open_user_menu()
        self.teacher.find(By.LINK_TEXT, 'Question Library').click()
        self.teacher.find(
            By.XPATH,
            '//div[@class="section"]//span[@class="chapter-section" ' +
            'and @data-chapter-section="1.2"]').click()
        self.teacher.driver.execute_script(
            "window.scrollTo(0, document.body.scrollHeight);")
        self.teacher.find(By.XPATH,
                          '//button[text()="Show Questions"]').click()
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//div[@class="exercises"]')))
        self.teacher.sleep(1)
        i = 1
        question = None
        # loop finding a question that is not yet excleded
        # there are 9 question in the exact textbook and chpater this test
        # is searching. limiting loop at 7 incase questions are removed.
        while i < 8:
            question = self.teacher.find(
                By.XPATH, '//div[@class="exercises"]/div[' + str(i) + ']')
            if ('is-selected' not in question.get_attribute('class')):
                break
            i += 1
        Assignment.scroll_to(self.teacher.driver, question)
        self.teacher.sleep(1)
        actions = ActionChains(self.teacher.driver)
        actions.move_to_element(question)
        # way to stall because not sure how to add wait in action chain
        for _ in range(50):
            actions.move_by_offset(-1, 0)
        actions.click()
        actions.move_by_offset(-50, -300)
        actions.perform()
        self.teacher.sleep(0.5)
        question_excluded = self.teacher.find(
            By.XPATH, '//div[@class="exercises"]/div[' + str(i) +
            ']').get_attribute('class')
        assert ('is-selected' in question_excluded), 'question not excluded'
        self.ps.test_updates['passed'] = True
Example #45
0
    def __init__(self,
                 username,
                 password,
                 site='https://tutor-qa.openstax.org',
                 email=None,
                 email_username=None,
                 email_password=None,
                 driver_type='chrome',
                 capabilities=None,
                 pasta_user=None,
                 wait_time=DEFAULT_WAIT_TIME,
                 opera_driver='',
                 existing_driver=None,
                 **kwargs):
        """
        Base user constructor.

        username (string): website username
        password (string): website password
        site (string): website URL
        driver_type (string): web browser type
        pasta_user (PastaSauce): optional API access for saucelabs
        capabilities (dict): browser settings; copy object to avoid overwrite
            Defaults:
                DesiredCapabilities.ANDROID.copy()
                DesiredCapabilities.CHROME.copy()
                DesiredCapabilities.EDGE.copy()
                DesiredCapabilities.FIREFOX.copy()
                DesiredCapabilities.HTMLUNIT.copy()
                DesiredCapabilities.HTMLUNITWITHJS.copy()
                DesiredCapabilities.INTERNETEXPLORER.copy()
                DesiredCapabilities.IPAD.copy()
                DesiredCapabilities.IPHONE.copy()
                DesiredCapabilities.ORERA.copy()
                DesiredCapabilities.PHANTOMJS.copy()
                DesiredCapabilities.SAFARI.copy()
            Keys:
                platform
                browserName
                version
                javascriptEnabled
        wait (int): standard time, in seconds, to wait for Selenium commands
        opera_driver (string): Chromium location
        """
        self.username = username
        self.password = password
        parse = list(
            urlparse(site if urlparse(site).scheme else '%s%s' % ('//', site)))
        parse[0] = b'https'
        for index, value in enumerate(parse):
            parse[index] = value.decode('utf-8') if isinstance(value, bytes) \
                else value
        parse = ParseResult(*parse)
        self.url = parse.geturl()
        self.email = email
        self.email_username = email_username
        self.email_password = email_password
        self.assign = Assignment()
        super(User, self).__init__(driver_type=driver_type,
                                   capabilities=capabilities,
                                   pasta_user=pasta_user,
                                   wait_time=wait_time,
                                   opera_driver=opera_driver,
                                   existing_driver=existing_driver,
                                   **kwargs)
Example #46
0
 def scroll_to(self, target):
     """Scroll the browser window to bring the target into view."""
     Assignment.scroll_to(self.driver, target)
     return target