Beispiel #1
0
    def test_send_book_list_email(self):
        u = User(username='******', email='*****@*****.**')
        b1title = 'hello'
        b2title = 'world'
        b1 = Book(title=b1title,
                  author='b',
                  date_of_purchase=datetime.utcnow(),
                  notes='Test Notes')
        b2 = Book(title=b2title,
                  author='d',
                  date_of_purchase=datetime.utcnow(),
                  notes='Test Notes')

        db.session.add(u)
        db.session.add(b1)
        db.session.add(b2)
        db.session.commit()
        u.add_book_owned(b1)
        u.add_book_owned(b2)
        db.session.commit()
        b = u.owned_books()
        subject = 'test'
        sender = '*****@*****.**'
        recipients = '*****@*****.**'
        text_body = 'text mctest'
        html_body = '<div>testing</div>'
        mail = Mail(self.app)
        with mail.record_messages() as outbox:
            send_book_list_email(u, recipients, b)
            assert len(outbox) == 1
            book1 = outbox[0].body.find('hello')
            book2 = outbox[0].body.find('world')
            assert book1 > 0
            assert book2 > 0
Beispiel #2
0
def users_person_signup_new():
    """
        ---
        post:
          summary: Allows a person to sign up (first step)
          tags:
            - Users
          description:
            Creates a new person (unconfirmed, with no access rights and without access to any account) and sends a welcome e-mail.
          parameters:
            - name: "body"
              in: body
              description: "Person data"
              required: true
              schema:
                "$ref": '#/definitions/PersonSignupNewPOST'
          responses:
            204:
              description: Request was accepted
            400:
              description: Invalid parameters
            403:
              description: Signup disabled
    """
    if os.environ.get('ENABLE_SIGNUP',
                      'false').lower() not in ['true', 'yes', 'on', '1']:
        return "Signup disabled", 403

    if os.environ.get('SIGNUP_DISALLOW_TOR',
                      'true').lower() in ['true', 'yes', 'on', '1']:
        # if user is coming from Tor exit node, disallow signup:
        client_ip = flask.request.environ.get('HTTP_X_FORWARDED_FOR', None)
        if not client_ip:
            return "Could not determine client IP", 403
        if _is_tor_exit_node(client_ip):
            return "Sorry, Tor exit nodes are not allowed to signup due to abuse", 403

    user_id, confirm_pin = Person.signup_new(flask.request.get_json())
    person_data = Person.get(user_id)

    mail_subject = "Welcome to Grafolean!"
    # unless explicitly set otherwise, assume that backend and frontend have the same origin:
    frontend_origin = os.environ.get('FRONTEND_ORIGIN',
                                     flask.request.url_root).rstrip('/')
    mail_body_text = _generate_signup_mail_message(person_data['name'],
                                                   person_data['email'],
                                                   frontend_origin, user_id,
                                                   confirm_pin)

    msg = Message(mail_subject,
                  sender="*****@*****.**",
                  recipients=[person_data['email']],
                  body=mail_body_text)
    mail = Mail(flask.current_app)
    with mail.record_messages() as outbox:
        mail.send(msg)
        flask.g.outbox = outbox  # make sent messages accessible to tests

    return "", 204
Beispiel #3
0
def test_mail(flask_app):
    mailer = Mailer()
    mail = Mail(flask_app)
    #fl.testing = True
    with flask_app.test_request_context('/'):
        with mail.record_messages() as outbox:
            mailer.send_contact_request(
                ContactRequest("*****@*****.**", "test", "test")).send(mail)
            assert len(outbox) == 1
            assert outbox[0].subject == "[Contact] test"
Beispiel #4
0
def test_send_mail():
    app.config["TESTING"] = True
    mail = Mail(app)

    subject = "test"
    content = "<p> hi </p>"
    recipient = "*****@*****.**"
    with mail.record_messages() as outbox:
        email.send_mail(app, subject, content, recipient)
    assert len(outbox) == 1
    assert outbox[0].subject == subject
    assert content in outbox[0].html
    assert outbox[0].recipients == [recipient]
Beispiel #5
0
 def test_send_email(self):
     subject = 'test'
     sender = '*****@*****.**'
     recipients = ['*****@*****.**']
     text_body = 'text mctest'
     html_body = '<div>testing</div>'
     mail = Mail(self.app)
     with mail.record_messages() as outbox:
         send_email(subject, sender, recipients, text_body, html_body)
         assert len(outbox) == 1
         assert outbox[0].subject == "test"
         assert outbox[0].sender == sender
         assert outbox[0].recipients == recipients
         assert outbox[0].body == text_body
Beispiel #6
0
def users_person_forgot_password():
    """
        ---
        post:
          summary: Sends an email with a reset password link
          tags:
            - Users
          description:
            If given an existing e-mail address, sends an e-mail message with a password reset link.
          parameters:
            - name: "body"
              in: body
              description: "E-mail address"
              required: true
              schema:
                "$ref": '#/definitions/ForgotPasswordPOST'
          responses:
            204:
              description: Request was accepted
            400:
              description: Invalid parameters
            500:
              description: Mail sending not setup
    """
    if not flask.current_app.config.get('MAIL_SERVER', None):
        return "Mail sending not setup", 500

    user_id, confirm_pin = Person.forgot_password(flask.request.get_json())
    if not user_id:
        return "Email does not correspond to any registered user", 400

    person_data = Person.get(user_id)
    mail_subject = "Grafolean password reset link"
    # unless explicitly set otherwise, assume that backend and frontend have the same origin:
    frontend_origin = os.environ.get('FRONTEND_ORIGIN',
                                     flask.request.url_root).rstrip('/')
    mail_body_text = _generate_forgot_password_message(frontend_origin,
                                                       user_id, confirm_pin)

    msg = Message(mail_subject,
                  sender="*****@*****.**",
                  recipients=[person_data['email']],
                  body=mail_body_text)
    mail = Mail(flask.current_app)
    with mail.record_messages() as outbox:
        mail.send(msg)
        flask.g.outbox = outbox  # make sent messages accessible to tests

    return "", 204
Beispiel #7
0
class MailHandler:

    def init_app(self, app):
        app.config.setdefault('DISABLE_MAIL', False)
        if not app.config['DISABLE_MAIL']:
            self.mail = Mail(app)
        else:
            self.mail = None

    def send(self, body=None, recipient=None, subject=None):
        if self.mail:
            msg = Message(subject=subject, body=body)
            msg.add_recipient(recipient)
            return self.mail.send(msg)

    def record_messages(self, *args, **kwargs):
        if self.mail:
            return self.mail.record_messages(*args, **kwargs)
Beispiel #8
0
class TestClient(unittest.TestCase):
    def setUp(self) -> None:
        self.app = create_app("testing")
        self.mail = Mail(self.app)
        self.context = self.app.test_request_context()
        self.context.push()
        self.client = self.app.test_client()
        db.create_all()
        admin = User(name="andyzhou")
        admin.set_password("PasswordForTesting")
        db.session.add(admin)
        db.session.commit()

    def tearDown(self) -> None:
        db.drop_all()
        db.session.remove()
        self.context.pop()

    def login_as_admin(self):
        data = {"name": "andyzhou", "password": "******"}
        response = self.client.post("/admin/login",
                                    data=data,
                                    follow_redirects=True)
        return response

    def create_article(self):
        data = {
            "name": fake.name(),
            "password": "******",
            "date": fake.date_this_year(),
            "title": fake.sentence(),
            "content": fake.text(200),
        }
        response = self.client.post("/articles/new",
                                    data=data,
                                    follow_redirects=True)
        return response

    def create_feedback(self):
        data = {"name": fake.name(), "body": fake.text(100)}
        response = self.client.post("/feedback/", data=data)
        return response

    def test_app_exists(self):
        self.assertIsNotNone(self.app)

    def test_app_is_testing(self):
        self.assertTrue(self.app.config["TESTING"])

    def test_200(self):
        self.assertEqual(self.client.get("/").status_code, 200)
        self.assertEqual(self.client.get("/index/").status_code, 200)
        self.assertEqual(self.client.get("/main/").status_code, 200)
        self.assertEqual(self.client.get("/articles/").status_code, 200)
        self.assertEqual(self.client.get("/feedback/").status_code, 200)
        self.assertEqual(self.client.get("/members/").status_code, 200)
        self.assertEqual(self.client.get("/video/").status_code, 200)
        self.assertEqual(self.client.get("/about/").status_code, 200)
        self.assertEqual(self.client.get("/kzkt/").status_code, 200)

    def test_401(self):
        self.assertEqual(self.client.get("/admin").status_code, 401)

    def test_404(self):
        self.assertEqual(self.client.get("/thisDoesn'tExist").status_code, 404)

    def test_500(self):
        @self.app.route("/500")
        def internal_server_error_for_testing():
            abort(500)

        response = self.client.get("/500")
        received_data = response.get_data(as_text=True)
        self.assertEqual(response.status_code, 500)
        self.assertIn("500 Internal Server Error", received_data)
        self.assertIn("nav", received_data)

    def test_400(self):
        @self.app.route("/400")
        def internal_server_error_for_testing():
            abort(400)

        response = self.client.get("/400")
        received_data = response.get_data(as_text=True)
        self.assertEqual(response.status_code, 400)
        self.assertIn("400 Bad Request", received_data)
        self.assertIn("nav", received_data)

    def test_add_article(self):
        article = Article(title="Test",
                          author="Test",
                          date="Test",
                          content="Test")
        self.assertEqual(str(article), "<Article Test>")
        db.session.add(article)
        db.session.commit()
        self.assertIsNotNone(Article.query_by_id(1))
        self.assertEqual(self.client.get("/articles/").status_code, 200)
        article.delete()
        self.assertIsNone(Article.query_by_id(1))

    def test_post_article(self):
        data = {
            "name": fake.name(),
            "password": fake.password(),
            "date": fake.date_this_year(),
            "title": fake.sentence(),
            "content": fake.text(200),
        }
        response = self.client.post("/articles/new",
                                    data=data,
                                    follow_redirects=True)
        received_data = response.get_data(as_text=True)
        self.assertIn("Wrong Password", received_data)
        self.assertEqual(Article.query.count(), 0)
        response = self.create_article()
        received_data = response.get_data(as_text=True)
        self.assertIn("Success", received_data)
        self.assertEqual(Article.query.count(), 1)

    def test_feedback(self):
        fake_name = fake.name()
        fake_body = fake.text(100)
        data = {"name": fake_name, "body": fake_body}
        response = self.client.post("/feedback/", data=data)
        self.assertEqual(response.status_code, 200)
        received_data = response.get_data(as_text=True)
        self.assertIn(fake_body, received_data)

    def test_emails(self):
        with self.mail.record_messages() as outbox:
            msg = Message(
                recipients=self.app.config["ADMIN_EMAIL_LIST"],
                subject="LSFD202201 Project Unittest",
                body="Plain Text",
                html="<strong>HTML</strong> <em>Content</em>",
            )
            self.mail.send(msg)
            self.assertGreater(len(outbox), 0)
            self.assertEqual(outbox[0].subject, "LSFD202201 Project Unittest")

    def test_admin_basic(self):
        response = self.client.get("/admin/logout")
        self.assertEqual(response.status_code, 401)
        response = self.client.get("/admin")
        self.assertEqual(response.status_code, 401)
        response = self.client.get("/admin/feedbacks")
        self.assertEqual(response.status_code, 401)
        response = self.client.get("/admin/login")
        self.assertEqual(response.status_code, 200)
        self.login_as_admin()
        response = self.client.get("/admin/login")
        self.assertEqual(response.status_code, 302)
        response = self.client.get("/admin")
        self.assertEqual(response.status_code, 200)
        self.create_article()
        response = self.client.get("/admin/articles/edit/1")
        self.assertEqual(response.status_code, 200)
        response = self.client.get("/admin/feedbacks")
        self.assertEqual(response.status_code, 200)
        response = self.client.get("/admin/logout")
        self.assertEqual(response.status_code, 302)

    def test_admin_login(self):
        data = {"name": "andyzhou", "password": "******"}
        response = self.client.post("/admin/login",
                                    data=data,
                                    follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        received_data = response.get_data(as_text=True)
        self.assertIn("Invalid username", received_data)
        data["password"] = "******"
        response = self.login_as_admin()
        received_data = response.get_data(as_text=True)
        self.assertIn("Welcome, Administrator", received_data)

    def test_admin_delete_article(self):
        self.login_as_admin()
        self.create_article()
        response = self.client.post("/admin/articles/delete/1")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(Article.query.all()), 0)

    def test_admin_edit_article(self):
        self.login_as_admin()
        self.create_article()
        fake_text = fake.text(200)
        data = {"content": fake_text}
        response = self.client.post("/admin/articles/edit/1",
                                    data=data,
                                    follow_redirects=True)
        self.assertEqual(response.status_code, 200)
        received_data = response.get_data(as_text=True)
        self.assertIn("Edit Succeeded!", received_data)
        print()
        article = Article.query_by_id(1)
        self.assertEqual(article.content, fake_text)

    def test_admin_delete_feedback(self):
        self.login_as_admin()
        self.create_feedback()
        self.assertGreater(len(Feedback.query.all()), 0)
        response = self.client.post("/admin/feedback/delete/1")
        self.assertEqual(response.status_code, 200)
        received_data = response.get_data(as_text=True)
        self.assertIn("deleted", received_data)
Beispiel #9
0
app.config['MAIL_USE_SSL'] = mail_SSL
app.config['MAIL_USE_TLS'] = mail_TLS
app.config['MAIL_USERNAME'] = mail_user
app.config['MAIL_PASSWORD'] = mail_pass
app.config['MAIL_SUPPRESS_SEND'] = False

# Create database connection object
db = MongoEngine(app)
#Bootstrap
Bootstrap(app)
#Setup Mail
mail = Mail(app)
mail.init_app(app)

# mail test
with mail.record_messages() as outbox:
    mail.send_message(subject='testing',
                      body='test',
                      recipients=['*****@*****.**'])

    assert len(outbox) == 1
    assert outbox[0].subject == "testing"

# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app,
                    user_datastore,
                    confirm_register_form=ExtendedConfirmRegisterForm)
#security = Security(app, user_datastore)

Beispiel #10
0
def test_valid_signup_information_with_account_activation(app, client):
    valid_email = '*****@*****.**'
    with client:
        try:
            response = client.get('/signup')
            contents = response.data.decode(encoding='utf-8')
            m = AUTHENTICITY_TOKEN_PATTERN.search(contents)
            assert len(m.groups()) == 1
            token = m.groups()[0]

            before_count = User.count()
            user = User(name='Example User',
                        email=valid_email,
                        password='******',
                        password_confirmation='password')

            mail = Mail(app)
            with mail.record_messages() as outbox:
                response = client.post('/users',
                                       data={
                                           'name': user.name,
                                           'email': user.email,
                                           'password': user.password,
                                           'password_confirmation':
                                           user.password_confirmation,
                                           'authenticity_token': token
                                       },
                                       follow_redirects=True)
                assert len(outbox) == 1

            # activation状態をデータベースから読み出す
            user = User.find_by(email=user.email)[0]
            assert not user.activated

            # activation digestが作られていることを確認する
            assert user.activation_digest

            # テストからactivation tokenを使用するためにtoken, digestを再設定する
            user.activation_token = User.new_token()
            digest = User.digest(user.activation_token)
            user.update_attribute('activation_digest', digest)

            # 有効化していない状態でログインしてみる
            log_in_as(client, user.email)
            assert not is_logged_in()
            # 有効化トークンが不正な場合
            url = url_for('account_activations.edit',
                          id='invalid token',
                          email=user.email,
                          _external=True)
            client.get(url, follow_redirects=True)
            assert not is_logged_in()
            # トークンは正しいがメールアドレスが無効な場合
            url = url_for('account_activations.edit',
                          id=user.activation_token,
                          email='wrong',
                          _external=True)
            client.get(url, follow_redirects=True)
            assert not is_logged_in()
            # 有効化トークンが正しい場合
            url = url_for('account_activations.edit',
                          id=user.activation_token,
                          email=user.email,
                          _external=True)
            response = client.get(url, follow_redirects=True)
            contents = response.data.decode(encoding='utf-8')
            user.reload()
            assert user.activated
            ref = render_template('users/show.html', user=user)
            assert are_same_templates(ref, contents)
            assert is_logged_in()
        finally:
            # 登録したユーザーを削除
            users = User.find_by(email=valid_email)
            if users:
                users[0].destroy()
Beispiel #11
0
app.config['MAIL_USE_TLS'] = mail_TLS
app.config['MAIL_USERNAME'] = mail_user
app.config['MAIL_PASSWORD'] = mail_pass 
app.config['MAIL_SUPPRESS_SEND'] = False


# Create database connection object
db = MongoEngine(app)
#Bootstrap
Bootstrap(app)
#Setup Mail
mail = Mail(app)
mail.init_app(app)

    # mail test
with mail.record_messages() as outbox:
    mail.send_message(subject='testing',
                      body='test',
                      recipients=['*****@*****.**'])

    assert len(outbox) == 1
    assert outbox[0].subject == "testing"


# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
security = Security(app, user_datastore, confirm_register_form=ExtendedConfirmRegisterForm)
#security = Security(app, user_datastore)


@app.route('/')
Beispiel #12
0
class FlaskrTestCase(unittest.TestCase):

    def setUp(self):
        self.db_fd, self.temp_filepath = tempfile.mkstemp()
        database_path = 'sqlite:///{}'.format(self.temp_filepath)
        app.config['SQLALCHEMY_DATABASE_URI'] = database_path
        app.config['TESTING'] = True
        self.mail = Mail(app)
        self.app = app.test_client()

        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        os.close(self.db_fd)
        os.remove(self.temp_filepath)

    def test_empty_db(self):
        entries = db.session.query(Request).all()
        assert len(entries) == 0

    def test_get_index(self):
        response = self.app.get("/")
        assert response.status_code == 200

    def test_make_request(self):
        with self.mail.record_messages() as outbox:
            example_data = dict(id='foobar',
                                email='*****@*****.**',
                                email_confirm='*****@*****.**',
                                captcha='Berlin'
                                )
            response = self.app.post('/',
                                     data=example_data,
                                     follow_redirects=True)

            assert response.status_code == 200
            entries = db.session.query(Request).all()
            assert len(entries) == 1
            assert len(outbox) == 1
            assert outbox[0].subject == "Deine Anfrage für das Freifunk VPN ist eingegangen!"
            assert "Hallo Freifunka!" in outbox[0].body


    def test_duplicate_id(self):
        with self.mail.record_messages() as outbox:
            example_data = dict(id='foobar',
                                email='*****@*****.**',
                                email_confirm='*****@*****.**',
                                captcha='Berlin'
                                )
            response = self.app.post('/',
                                     data=example_data,
                                     follow_redirects=True)
            assert response.status_code == 200
            entries = db.session.query(Request).all()
            assert len(entries) == 1
            assert len(outbox) == 1
            assert outbox[0].subject == "Deine Anfrage für das Freifunk VPN ist eingegangen!"
            assert "Hallo Freifunka!" in outbox[0].body

        response = self.app.post('/',
                                 data=example_data,
                                 follow_redirects=True)

        assert 'Id already exists.' in str(response.data)

        # The new entry should not have been added so we should
        # still only have on entry
        entries = db.session.query(Request).all()
        assert len(entries) == 1

    def test_invalid_request_too_short(self):
        example_data = dict(id='a',
                            email='*****@*****.**',
                            email_confirm='*****@*****.**',
                            captcha='Berlin'
                            )
        response = self.app.post('/',
                                 data=example_data,
                                 follow_redirects=True)

        entries = db.session.query(Request).all()
        assert len(entries) == 0

    def test_invalid_request_underscore(self):
        example_data = dict(id='underscores_not_allowed',
                            email='*****@*****.**',
                            email_confirm='*****@*****.**',
                            captcha='Berlin'
                            )
        response = self.app.post('/',
                                 data=example_data,
                                 follow_redirects=True)

        entries = db.session.query(Request).all()
        assert len(entries) == 0

    def test_invalid_request_mail_to_long(self):
        example_data = dict(id='validusername',
                            email='a'*40+'@foo.bar',
                            email_confirm='a'*40+'@foo.bar',
                            captcha='Berlin'
                            )
        response = self.app.post('/',
                                 data=example_data,
                                 follow_redirects=True)

        entries = db.session.query(Request).all()
        assert len(entries) == 0