Exemplo n.º 1
0
class MailingListIntegrationTestCase(LiveServerTestCase):
    def setUp(self):
        # Create MailingList (newsletter) object
        self.mailing_list_1 = MailingList.objects.create(
            mailing_list_name="news1",
            mailing_list_token="token1",
            list_active=True,
        )
        self.mailing_list_2 = MailingList.objects.create(
            mailing_list_name="news2",
            mailing_list_token="token2",
            contact_frequency_weeks=4,
            list_active=True,
        )
        # Create MailingList (petition) object
        self.mailing_list_3 = MailingList.objects.create(
            mailing_list_name="petition1",
            mailing_list_token="token3",
            list_active=True,
            is_petition=True,
        )
        self.mailing_list_4 = MailingList.objects.create(
            mailing_list_name="petition2",
            mailing_list_token="token4",
            list_active=True,
            is_petition=True,
        )
        # Create two Petition (petition) object
        self.petition_1 = Petition.objects.create(
            mailing_list=self.mailing_list_3,
            slug="slug1",
            petition1_md="First sentence",
        )
        self.petition_2 = Petition.objects.create(
            mailing_list=self.mailing_list_4,
            slug="slug2",
            petition1_md="First sentence 2",
        )
        self.user = User.objects.create_user(username='******',
                                             password='******',
                                             email="*****@*****.**")
        self.user.save()
        self.logged_client = Client()
        self.logged_client.login(username='******', password='******')
        self.superuser = \
            User.objects.create_superuser(username='******',
                                          password='******',
                                          email="*****@*****.**")
        self.superuser.save()
        self.admin_client = Client()
        self.admin_client.login(username='******', password='******')
        # Create a topicblog page for testing quick sign up
        self.home = TopicBlogItem.objects.create(
            slug="home",
            date_modified=datetime.now(timezone.utc),
            publication_date=datetime.now(timezone.utc),
            first_publication_date=datetime.now(timezone.utc),
            user=self.superuser,
            template_name="topicblog/content.html",
            title="home-title")
        # Create the default mailing list
        self.mailing_list_default = MailingList.objects.create(
            mailing_list_name="general-quarterly",
            mailing_list_token="general-quarterly",
            contact_frequency_weeks=12,
            list_active=True,
        )
        # Create MailingListEvent object
        self.mailing_event_1 = MailingListEvent.objects.create(
            user=self.user, mailing_list=self.mailing_list_1,
            event_type=MailingListEvent.EventType.SUBSCRIBE)

        self.mailing_event_2 = MailingListEvent.objects.create(
            user=self.superuser, mailing_list=self.mailing_list_2,
            event_type=MailingListEvent.EventType.SUBSCRIBE)

        self.cookie_user = self.logged_client.cookies['sessionid'].value
        self.cookie_staff = \
            self.admin_client.cookies['sessionid'].value

        options = Options()
        options.add_argument("--headless")
        options.add_argument("--disable-extensions")
        self.selenium = WebDriver(ChromeDriverManager().install(),
                                  options=options)
        self.selenium.implicitly_wait(5)

    def tearDown(self):
        # Close the browser
        self.selenium.quit()

    # def testing_quick_form_logged_out(self):
    #     self.selenium.get('%s%s' % (self.live_server_url,
    #                                 reverse("topicblog:view_item_by_slug",
    #                                         kwargs={
    #                                             "the_slug": self.home.slug
    #                                         })))
    #     email_input = self.selenium.find_element_by_id("id_email")
    #     email_input.send_keys("*****@*****.**")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     # pass the captcha only work on dev mod
    #     captcha_input = self.selenium.find_element_by_id("id_captcha_1")
    #     captcha_input.send_keys("PASSED")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     user = User.objects.filter(email="*****@*****.**").first()
    #     self.assertIsNotNone(
    #         user,
    #         msg="The user was not created during mailing list signup")
    #     mailing_list_event = MailingListEvent.objects.filter(user=user).first()
    #     self.assertIsNotNone(mailing_list_event,
    #                          msg="The mailing event is not created"
    #                              "on quick sign up")

    #     self.assertEqual(
    #         mailing_list_event.event_type, "sub",
    #         msg="The user is not subscribed to the default mailing list")

    def testing_quick_form_logged_in(self):
        # Get on mobilitains website
        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("topicblog:view_item_by_slug",
                                            kwargs={
                                                "the_slug": self.home.slug
                                            })))
        # Add a session cookie to the browser (refused if not already on the
        # website)
        self.selenium.add_cookie(
            {'name': 'sessionid', 'value': self.cookie_user,
             'secure': False, 'path': '/'})
        # Refresh the page to get the proper display
        self.selenium.refresh()
        # because we're already logged in, we're subbed to the default
        # list without captcha
        self.selenium.find_element_by_css_selector(
            "form button[type=submit]").click()
        # We wait until next page is loaded (confirmation page)
        WebDriverWait(self.selenium, 5).until(
            EC.url_contains(reverse("mailing_list:quick_signup"))
        )
        # We used the self.user's cookie to connect to the website
        user = User.objects.filter(email=self.user.email).first()
        self.assertIsNotNone(
            user,
            msg="The user created during setUp does not exist")
        mailing_list_event = MailingListEvent.objects.filter(user=user).first()
        self.assertIsNotNone(mailing_list_event,
                             msg="The mailing event was not created "
                                 "on quick sign up")

        self.assertEqual(mailing_list_event.event_type, "sub",
                         msg="The user is not sub on the default mailing list")

    # def testing_quick_form_fail_captcha_logged_out(self):
    #     self.selenium.get('%s%s' % (self.live_server_url,
    #                                 reverse("topicblog:view_item_by_slug",
    #                                         kwargs={
    #                                             "the_slug": self.home.slug
    #                                         })))
    #     email_input = self.selenium.find_element_by_id("id_email")
    #     email_input.send_keys("*****@*****.**")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     # fail the capcha
    #     captcha_input = self.selenium.find_element_by_id("id_captcha_1")
    #     captcha_input.send_keys("Notgood")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     # pass the captcha only work on dev mod
    #     captcha_input = self.selenium.find_element_by_id("id_captcha_1")
    #     captcha_input.send_keys("PASSED")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     user = User.objects.filter(email="*****@*****.**").first()
    #     self.assertIsNotNone(user,
    #                          msg="The user is not created on quick sign up")
    #     mailing_list_event = MailingListEvent.objects.filter(user=user).first()
    #     self.assertIsNotNone(mailing_list_event,
    #                          msg="The mailing event is not created"
    #                              "on quick sign up")

    #     self.assertEqual(mailing_list_event.event_type, "sub",
    #                      msg="The user is not sub on the default mailing list")

    # def testing_quick_form_fail_captcha_logged_in(self):
    #     self.selenium.get('%s%s' % (self.live_server_url,
    #                                 reverse("topicblog:view_item_by_slug",
    #                                         kwargs={
    #                                             "the_slug": self.home.slug
    #                                         })))
    #     email_input = self.selenium.find_element_by_id("id_email")
    #     email_input.send_keys("*****@*****.**")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     # fail the capcha
    #     captcha_input = self.selenium.find_element_by_id("id_captcha_1")
    #     captcha_input.send_keys("Notgood")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     # pass the captcha only work on dev mod
    #     captcha_input = self.selenium.find_element_by_id("id_captcha_1")
    #     captcha_input.send_keys("PASSED")
    #     self.selenium.find_element_by_css_selector(
    #         "form button[type=submit]").click()
    #     user = User.objects.filter(email="*****@*****.**").first()
    #     self.assertIsNotNone(user,
    #                          msg="The user is not created on quick sign up")
    #     mailing_list_event = MailingListEvent.objects.filter(user=user).first()
    #     self.assertIsNotNone(mailing_list_event,
    #                          msg="The mailing event is not created"
    #                              "on quick sign up")

    #     self.assertEqual(mailing_list_event.event_type, "sub",
    #                      msg="The user is not sub on the default mailing list")

    def testing_acces_with_get_to_the_quick_form(self):
        quick_signup_url = reverse("mailing_list:quick_signup")
        self.selenium.get(f"{self.live_server_url}{quick_signup_url}")
        index_url = f"{self.live_server_url}{reverse('index')}#newsletter"
        self.assertEqual(self.selenium.current_url, index_url,
                         msg="User SHOULD be redirect to index page")

    def testing_user_status_page_subscribe_to_newsletter(self):
        old_event = user_current_state(self.user, self.mailing_list_2)
        self.assertEqual(old_event.event_type, "unsub")
        user_status_url = reverse("mailing_list:user_status")
        self.selenium.get(f"{self.live_server_url}{user_status_url}")
        self.selenium.add_cookie(
            {'name': 'sessionid', 'value': self.cookie_user,
             'secure': False, 'path': '/'})
        self.selenium.get(f"{self.live_server_url}{user_status_url}")
        self.selenium.find_element_by_css_selector(
            f"#id-ml-{self.mailing_list_2.id} form button[type=submit]"
        ).click()
        a_html = \
            self.selenium.find_element_by_css_selector(
                f"#id-ml-{self.mailing_list_2.id} div a").get_attribute(
                    'innerHTML')
        new_event = user_current_state(self.user, self.mailing_list_2)
        # Check if the event is updated
        self.assertEqual(new_event.event_type, "sub",
                         msg="The event was not updated")
        self.assertEqual(a_html, "Se désabonner",
                         msg="The page is not updated")

    def testing_user_status_page_unsubscribe_to_newsletter(self):
        old_event = user_current_state(self.user, self.mailing_list_1)
        self.assertEqual(old_event.event_type, "sub")
        user_status_url = reverse("mailing_list:user_status")
        self.selenium.get(f"{self.live_server_url}{user_status_url}")
        self.selenium.add_cookie(
            {'name': 'sessionid', 'value': self.cookie_user,
             'secure': False, 'path': '/'})
        self.selenium.get(f"{self.live_server_url}{user_status_url}")
        self.selenium.find_element_by_css_selector(
            f"#id-ml-{self.mailing_list_1.id} a").click()
        self.selenium.find_element_by_css_selector(
            "form button[type=submit]").click()
        button_html = self.selenium.find_element_by_css_selector(
            f"#id-ml-{self.mailing_list_1.id} div button").get_attribute(
                'innerHTML')
        new_event = user_current_state(self.user, self.mailing_list_2)
        # Check if the event is updated
        self.assertEqual(new_event.event_type, "unsub",
                         msg="The event was not updated")
        self.assertEqual(button_html, "S'abonner",
                         msg="The page was not updated")
Exemplo n.º 2
0
browser.get('https://www.taobao.com')
# 将浏览器最大化显示
browser.maximize_window()
print('windows', browser.get_window_size())
# 隐性等待页面加载完成,如果一个元素获取不到,会等待30s
browser.implicitly_wait(30)

try:
    with open('cookie.txt', 'rb') as f:
        cookies = pickle.load(f)
except Exception as e:
    print(e)
else:
    for cookie in cookies:
        try:
            browser.add_cookie(cookie)
        except Exception as e:
            print(cookie)
    browser.refresh()

print("*" * 100)
print(browser.get_cookies())
print(len(browser.get_cookies()))
print("*" * 100)


class TaobaoSpider:
    def __init__(self, driver):
        self.driver = driver

    def search_action(self):
class TestsTopicItemForm(LiveServerTestCase):
    def setUp(self):
        # all permission
        edit_permission = Permission.objects.get(codename="tbi.may_edit")
        view_permission = Permission.objects.get(codename="tbi.may_view")
        publish_permission = Permission.objects.get(codename="tbi.may_publish")
        publish_self_permission = Permission.objects.get(
            codename="tbi.may_publish_self")
        # Create a user with all permission
        self.user = User.objects.create_user(username='******',
                                             password='******')
        self.user.user_permissions.add(
            edit_permission,
            view_permission,
            publish_permission,
            publish_self_permission,
        )
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save()
        # Create a user that cant self publish editor 1
        self.user_editor = User.objects.create_user(username='******',
                                                    password='******')
        self.user_editor.user_permissions.add(
            edit_permission,
            view_permission,
            publish_permission,
        )
        self.user_editor.is_staff = True
        self.user_editor.save()
        # Create a user that cant self publish editor 2
        self.user_editor_two = User.objects.create_user(username='******',
                                                        password='******')
        self.user_editor_two.user_permissions.add(
            edit_permission,
            view_permission,
            publish_permission,
        )
        self.user_editor_two.is_staff = True
        self.user_editor_two.save()
        # Create client for user
        self.user_editor_client = Client()
        self.user_editor_two_client = Client()
        # Log user into the client
        self.client.login(username='******', password='******')
        self.user_editor_client.login(username='******',
                                      password='******')
        self.user_editor_two_client.login(username='******', password='******')
        # Take the session id cookie for log into selenium
        self.cookie_admin = self.client.cookies['sessionid'].value
        self.cookie_editor = self.user_editor_client.cookies['sessionid'].value
        self.cookie_editor_two = (
            self.user_editor_two_client.cookies['sessionid'].value)
        """ Launch the browser the path of the browser will be
         auto added with the webdriver_manager package and wait 10 sec
        """
        options = Options()
        options.add_argument("--headless")
        options.add_argument("--disable-extensions")
        self.selenium = WebDriver(ChromeDriverManager().install(),
                                  options=options)

        self.selenium.implicitly_wait(5)

    def tearDown(self):
        # Close the browser
        self.selenium.quit()

    def fill_the_form_and_publish(self,
                                  slug,
                                  title,
                                  body_1="body 1",
                                  body_2="body 2",
                                  body_3="body 3",
                                  edit=False):
        """Fill the topicblog item form and publish
        """
        if not edit:
            slug_input = self.selenium.find_element_by_name("slug")
            slug_input.send_keys(slug)
        title_input = self.selenium.find_element_by_name("title")
        title_input.clear()
        title_input.send_keys(title)
        select = Select(self.selenium.find_element_by_name("template"))
        select.select_by_value("topicblog/content.html")
        self.selenium.find_element_by_link_text("Contenu (1)").click()
        body_text_1_md_input = self.selenium.find_element_by_id(
            "id_body_text_1_md")
        body_text_1_md_input.clear()
        body_text_1_md_input.send_keys(body_1)
        body_text_2_md_input = self.selenium.find_element_by_id(
            "id_body_text_2_md")
        body_text_2_md_input.clear()
        body_text_2_md_input.send_keys(body_2)
        self.selenium.find_element_by_link_text("Contenu (2)").click()
        body_text_3_md_input = self.selenium.find_element_by_id(
            "id_body_text_3_md")
        body_text_3_md_input.clear()
        body_text_3_md_input.send_keys(body_3)
        self.selenium.find_element_by_name("sauvegarder").click()
        self.selenium.find_element_by_xpath(
            "//input[@value='Publier']").click()

    def test_user_permited_create_auto_publish(self):
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie_admin,
            'secure': False,
            'path': '/'
        })
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.fill_the_form_and_publish("test-slug-staff", "title item")
        item_staff = TopicBlogItem.objects.filter(slug="test-slug-staff")[0]
        self.assertIsNotNone(item_staff,
                             msg="The item created by the super user"
                             " is not in the database")
        # Go to the user view
        self.selenium.find_element_by_link_text("Visualiser (usager)").click()
        """Get the body innerHTML and check if
        this is what we send in the form
        """
        body_app_content = self.selenium.find_element_by_id("app_content")
        body_html = body_app_content.get_attribute('innerHTML')
        self.assertHTMLEqual(body_html,
                             "<p>body 1</p><p>body 2</p><p>body 3</p>",
                             msg="The body innerHTML is not the same"
                             " as what we send to the form")

    def test_editor_create_item_but_cant_publish(self):
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie_editor,
            'secure': False,
            'path': '/'
        })
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        slug = 'test-slug-editor'
        self.fill_the_form_and_publish(slug, 'title item')
        # Check if the item is on the databse and the publication should equal to none.
        item_editor = TopicBlogItem.objects.filter(slug="test-slug-editor")[0]
        self.assertIsNotNone(item_editor,
                             msg="The item created by the editor"
                             " is not in the database")
        self.assertIsNone(item_editor.publication_date,
                          msg="The publication date is not none")
        # Check if the user get the 403 Forbidden
        body = self.selenium.find_element_by_tag_name("body")
        body_html = body.get_attribute('innerHTML')
        self.assertHTMLEqual(body_html,
                             "<h1>403 Forbidden</h1><p></p>",
                             msg="User can't self publish")
        # Check the user view
        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("topic_blog:view_item_by_slug",
                                            kwargs={"the_slug": slug})))
        """Get the body innerHTML and check if
        this is not found because this is not published
        """
        body_view = self.selenium.find_element_by_tag_name("body")
        body_view_html = body_view.get_attribute('innerHTML')
        self.assertHTMLEqual(
            body_view_html, "<h1>Not Found</h1><p>The requested resource "
            "was not found on this server.</p>")

    def test_editor_create_and_another_publish(self):
        # Create an item with the first editor that is not published
        self.item = TopicBlogItem.objects.create(
            slug="test-slug",
            user=self.user_editor,
            template_name="topicblog/content.html",
            body_text_1_md="body 1",
            body_text_2_md="body 2",
            body_text_3_md="body 3",
            title="Test-title")
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie_editor_two,
            'secure': False,
            'path': '/'
        })
        # Go to the admin view of the item that the first editor as created
        self.selenium.get('%s%s' % (self.live_server_url,
                                    reverse("topic_blog:view_item_by_pkid",
                                            kwargs={
                                                "pkid": self.item.id,
                                                "the_slug": self.item.slug,
                                            })))
        self.selenium.find_element_by_xpath(
            "//input[@value='Publier']").click()
        item_editor = TopicBlogItem.objects.filter(slug="test-slug")[0]
        # Check if publication date and first publication date is NOT none
        self.assertIsNotNone(item_editor.publication_date,
                             msg="The publication date should not be none")
        self.assertIsNotNone(item_editor.first_publication_date,
                             msg="The first publication date"
                             "should not be none")
        # Check the user view
        self.selenium.find_element_by_link_text("Visualiser (usager)").click()
        """Get the body innerHTML and check if
        this is what we send in the form
        """
        body_app_content = self.selenium.find_element_by_id("app_content")
        body_html = body_app_content.get_attribute('innerHTML')
        self.assertHTMLEqual(body_html,
                             "<p>body 1</p><p>body 2</p><p>body 3</p>",
                             msg="The body innerHTML is not the same"
                             " as what we send to the form")

    def test_edit_and_self_publish(self):
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie_admin,
            'secure': False,
            'path': '/'
        })
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.fill_the_form_and_publish(slug="test-edited", title="title-edit")
        # Go to the edit view
        self.selenium.find_element_by_link_text("Modifier").click()
        self.fill_the_form_and_publish(slug="",
                                       title="new title edited",
                                       body_1="new setence 1",
                                       body_2="new setence 2",
                                       body_3="new setence 3")

        # Check if the new title is on the database
        item_edited = TopicBlogItem.objects.filter(title="new title edited")[0]

        self.assertIsNotNone(item_edited,
                             msg="The item edited by the staff"
                             " is not in the database")
        # Go to the user view
        self.selenium.find_element_by_link_text("Visualiser (usager)").click()
        """Get the body innerHTML and check if
        this is what we send in the form
        """
        body_app_content = self.selenium.find_element_by_id("app_content")
        body_html = body_app_content.get_attribute('innerHTML')
        self.assertHTMLEqual(
            body_html,
            "<p>new setence 1</p><p>new setence 2</p><p>new setence 3</p>",
            msg="The body innerHTML is not the same"
            " as what we send to the form")

    def test_publish_an_unpublishable_item(self):
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie_admin,
            'secure': False,
            'path': '/'
        })
        self.selenium.get(
            '%s%s' % (self.live_server_url, reverse("topic_blog:new_item")))
        slug_input = self.selenium.find_element_by_name("slug")
        slug_input.send_keys("unpublishable")
        select = Select(self.selenium.find_element_by_name("template"))
        select.select_by_value("topicblog/content.html")
        self.selenium.find_element_by_name("sauvegarder").click()
        # Check if the item is on the databse and get the data for faking the publish
        item_unpublishable = TopicBlogItem.objects.filter(
            slug="unpublishable")[0]

        self.assertIsNotNone(item_unpublishable,
                             msg="The item created by the staff"
                             " is not in the database")
        # testing with the unpublishable item of the staff
        response_0 = self.client.post(
            reverse("topicblog:view_item_by_pkid",
                    kwargs={
                        "pkid": item_unpublishable.id,
                        "the_slug": item_unpublishable.slug
                    }))
        self.assertEqual(response_0.status_code,
                         500,
                         msg="try to pubilsh unpublishable item should return"
                         "HttpResponseServerError(code 500)")