Ejemplo n.º 1
0
def post_results(onlypass, domain, project, testsetid, user, buildnum):
    global globals_tc_result
    global globals_tcset_list
    global globals_name_contains_dot
    # query test instance id by test case name in test set
    for tc_ret in globals_tc_result:
        hpqc_testname = tc_ret['testname']
        if globals_name_contains_dot is False:
            hpqc_testname = hpqc_testname.split('.')[-1]
        # test case may not exist in wanted testset, so do a check.
        tc = [x for x in globals_tcset_list if x[1] == hpqc_testname]
        if len(tc):
            tc_ret['testinstanceid'] = tc[0][0]

    # filter cases whose name can't be found in testset
    # filter passed vs failed cases
    tc_notfound = [x for x in globals_tc_result if 'testinstanceid' not in x]
    tc_passed = [
        x for x in globals_tc_result
        if 'testinstanceid' in x and x['result'] == 'Passed'
    ]
    tc_failed = [
        x for x in globals_tc_result
        if 'testinstanceid' in x and x['result'] == 'Failed'
    ]
    url = QC_API_URL_RUNS % (domain, project)

    def upload_results(url, user, buildnum, tc_list, status):
        data = {
            'tester': user,
            'testInstanceIDs': ','.join(x['testinstanceid'] for x in tc_list),
            'status': status,
            'build': buildnum
        }
        ret = fetch_url(url, data=data)
        if ret is None:
            log.error('Failed to upload test results')
            raise Exception('Failed to upload test results')
        else:
            log.debug(ret)
            tc_output('Succeeded to upload %s cases' % status, tc_list)

    if len(tc_passed) > 0:
        upload_results(url, user, buildnum, tc_passed, 'Passed')

    if len(tc_failed) > 0 and onlypass is False:
        upload_results(url, user, buildnum, tc_failed, 'Failed')

    if tc_notfound:
        json_dump(logdir, 'hpqc_testcase_not_found', tc_notfound)
        subject = "Testcases NOT FOUND in testset[s]: %s" % testsetid
        body = [
            "  %s NOT_FOUND" % (x['testname'].ljust(80)) for x in tc_notfound
        ]
        notification.send_email(subject, body)
Ejemplo n.º 2
0
    def post(self):
        parser = parser = reqparse.RequestParser()
        parser.add_argument('line_id', location='json', required=True)
        parser.add_argument('product_code', location='json', required=True)
        parser.add_argument('phone_number', location='json', required=True)
        args = parser.parse_args()
        # butuh selected user
        selected_user = Users.query.filter_by(line_id=args['line_id']).first()
        # butuh selected product
        selected_product = Product.query.filter_by(
            code=args['product_code']).first()
        print(selected_product.id)
        saldo = get_balance()

        if int(selected_product.nominal) > int(saldo["data"]["balance"]):
            send_email(
                "*****@*****.**", "*****@*****.**",
                "Saldo Mobile Pulsa Harus Diisi",
                "Ada Transaksi Yang Melebihi Saldo Mobile Pulsa Bos, Segera Isi ulang saldo"
            )
            return {'status': "GAGAL"}, 403
        # new transaction
        new_transaction = Transactions(
            user_id=selected_user.id,
            phone_number=args['phone_number'],
            product_id=selected_product.id,
            operator=selected_product.operator,
            label='{} {}'.format(selected_product.operator,
                                 selected_product.nominal),
            nominal=selected_product.nominal,
            price=selected_product.price,
            created_at=datetime.now(timezone('Asia/Jakarta')))
        db.session.add(new_transaction)
        db.session.commit()

        # production = delete --TEST--
        new_transaction.order_id = 'TUKULSAORDER4-{}'.format(
            str(new_transaction.id))
        db.session.commit()

        marshal_trx = marshal(new_transaction, Transactions.response_fields)

        link_payment = midtrans_payment(
            order_id=new_transaction.order_id,
            label=new_transaction.label,
            phone_number=new_transaction.phone_number,
            display_name=selected_user.display_name,
            price=new_transaction.price)

        marshal_trx['link_payment'] = link_payment
        marshal_trx['status'] = 'SUKSES'

        # print(marshal_trx)
        return marshal_trx, 200, {'Content-Type': 'application/json'}
Ejemplo n.º 3
0
def create(payload):
    """Extracts key/relevant information from payload, runs tests, inserts commit info into database, notifies whether (un)successful and sends e-mail to author of commit

    Parameters:
    payload (str): String representative of a JSON file containing info on commit

    Returns:
    build_details (dict): Dictionary containing relevant information from payload
   """
    # Check that the branch is 'assessment'
    if payload['ref'] != "refs/heads/assessment":
        print("Branch is not 'assessment', ignoring.")
        return {}
    repo = payload['repository']['full_name']
    commit_id = payload['head_commit']['id']
    date = payload['head_commit']['timestamp'].replace("-", "").replace(
        ":", "").replace("T", "_")[:-5]

    result = subprocess.run(['sh', './ci.sh', repo, commit_id],
                            stdout=subprocess.PIPE,
                            stderr=STDOUT)
    ci_output = result.stdout.decode("utf-8")
    lint_successful = ci_output.find("Lint OK") != -1
    test_successful = ci_output.find("Test OK") != -1

    # Save build history
    build_details = {
        "commit_id": commit_id,
        "build_date": date,
        "build_logs": ci_output,
    }
    values = (commit_id, date, ci_output, "/builds/" + commit_id)
    conn = db.create_connection(r"commit_history")
    with conn:
        db.insert_commit(conn, values)

    # Notification
    is_successful = lint_successful and test_successful
    notification.update_commit_status(repo, commit_id, is_successful)

    # For sending email
    receiver_email = payload['head_commit']['author']['email']
    notification.send_email(values, receiver_email)

    return build_details
Ejemplo n.º 4
0
    def test_send_email_sends_build_details(self):
        sender_email = environ.get("EMAIL")

        commit_id = "04dbec97248ca15f8db8567efbe48b3b2e85a32e"
        date = "20200121"
        logs = "Building ... Testing ..."
        url = "/builds/" + commit_id

        values = [commit_id, date, logs, url]
        receiver_email = "*****@*****.**"

        mock_email_server = Mock()

        notification.send_email(values,
                                receiver_email,
                                email_sender=mock_email_server)

        mock_email_server.sendmail.assert_called_with(
            sender_email, receiver_email,
            'CI Server push update 04dbec97248ca15f8db8567efbe48b3b2e85a32e\n\nCommit ID: 04dbec97248ca15f8db8567efbe48b3b2e85a32e\nDate: 20200121\nBuild Log: Building ... Testing ...\nURL: /builds/04dbec97248ca15f8db8567efbe48b3b2e85a32e'
        )
Ejemplo n.º 5
0
def create_user(user):

    password = generate_password_hash(user['password'] +
                                      SECURITY_PASSWORD_SALT)
    token = generate_confirmation_token(user['email'])

    User.put_new_user(user['email'], user['firstName'], user['lastName'],
                      user['dob'], user['gender'], password)

    # confirm_url = url_for('confirm_email', token=token, _external=True)
    confirm_url = f"{FRONTEND}/confirm/{token}"
    subject = "Please confirm your email"
    bodyHtml = render_template_string(EMAIL_CONFIRMATION_HTML,
                                      confirm_url=confirm_url)
    bodyText = render_template_string(EMAIL_CONFIRMATION_TEXT,
                                      confirm_url=confirm_url)
    send_email(SENDER, user['email'], bodyHtml, bodyText, subject)
    return jsonify({
        'message':
        'Verification link is sent to your email ' + user['email'] +
        'click on the activation link and sign in.'
    })
Ejemplo n.º 6
0
    def put(self):
        parser = parser = reqparse.RequestParser()
        parser.add_argument('line_id', location='json', required=True)
        parser.add_argument('text', location='json')
        parser.add_argument('email', location='json')
        args = parser.parse_args()

        user_qry = Users.query.filter_by(line_id=args['line_id']).first()
        user_id = user_qry.id

        report_qry = Report.query.filter_by(user_id=user_id).order_by(
            desc(Report.id)).first()
        if args['text']:
            report_qry.text = report_qry.text + " " + str(args['text'])
        if args['email']:
            report_qry.email = args['email']
            # Generate security code
            size = 32
            char = string.ascii_letters + string.digits
            code = (''.join(random.choice(char) for _ in range(0, size)))
            report_qry.security_code = code
            message = template_notification.format(report_qry.order_id,
                                                   report_qry.order_id,
                                                   report_qry.text,
                                                   report_qry.created_at,
                                                   report_qry.email, code)
            subject = "Keluhan terkait Order {}".format(report_qry.order_id)
            send_email("*****@*****.**",
                       "*****@*****.**", subject, message)
            chat_qry = Chat.query.filter_by(chat_userid=user_id).first()
            chat_qry.status_report = False
        db.session.commit()

        return marshal(report_qry, Report.response_fields), 200, {
            'Content-Type': 'application/json'
        }
Ejemplo n.º 7
0
def testNotification(savesql, obj, testcase_id, error, final_status, user_id, tname):
	notification_type = parseByDot(obj, 'Type')
	test_info.append(notification_type)

	if notification_type == 'FAIL_COUNT':
		notification_count = parseByDot(obj, 'FailCount')
		sql = "SELECT fail_count, total_count from notifications where testcase_id=%s"
		cur.execute(sql, (testcase_id))
		curval = cur.fetchone()

		if curval is not None:
			if curval[0] != 0:
				if (final_status == 'SUCCESS') and (curval[0] % int(notification_count) == 0):
					savesql = "INSERT INTO notifications (user_id, testcase_id, notification_type, success_count, total_count, final_status, notification_count, testcase_name) VALUES (%s, %s, %s, %s, %s, 'SUCCESS', %s, %s) ON DUPLICATE KEY UPDATE fail_count=0, success_count=success_count+1, total_count=total_count+1, final_status=%s"
				elif (final_status == 'FAIL') and ((curval[0]+1) % int(notification_count) == 0):
					mylogger.info('Notification occured')
					test_info.append('Test failed %s time(s).' % notification_count)
					notification.send_email(error, test_info)
		
		cur.execute(savesql, (user_id, testcase_id, notification_type, 1, 1, int(notification_count), tname, final_status))
	elif notification_type == 'STATUS_CHANGE':
		sql = "SELECT final_status from notifications where testcase_id=%s"
		cur.execute(sql, (testcase_id))
		curval = cur.fetchone()
		cur.execute(savesql, (user_id, testcase_id, notification_type, 1, 1, 0, tname, final_status))

		if curval is not None:
			if curval[0] != final_status:
				mylogger.info('Notification occured')
				test_info.append('%s → %s' % (curval[0], final_status))
				notification.send_email(error, test_info)
		else:
			if final_status == 'FAIL':
				mylogger.info('Notification occured')
				test_info.append('First test failed.')
				notification.send_email(error, test_info)
Ejemplo n.º 8
0
			# check equal
			if set(previous_ip_list) == set(current_ip_list):
				print "sama"

				# only update 'last_checked_time' at previous log.
				write_log(command, previous_log['ip'], log_file_path)
				
			else:
				print "beda. send notification. write log file"

				# log previous
				log_file_name = "log/%s-%s.json" % (key, current_check_time)
				write_log(command, previous_log['ip'], log_file_name, previous_log['last_checked_time'])

				# log current
				write_log(command, current_ip_list, log_file_path)

				print "sending notification..."
				try:
					# send notification
					notification.send_email(key, command, previous_ip_list, previous_log['last_checked_time'], current_ip_list, current_check_time)
				except Exception, e:
					print e
					print "error while sending notification"
				
				print "done."

		else:
			# no log file to be compared, so write the new one.
			write_log(command, current_ip_list, log_file_path)
			print "no log file. print a new one."