Login Test with Jenkins and Symfony2 - database

I configured jenkins in order to automating the tests for my project. The unit tests work well. Now I want to do some test with my database. For example the login test: enter the username, the password (submit the form). Do you have an idea of how to do this? Thank you.
Here is the test I want to do but it does not work:
Get the home page, test if the link FAQ is present two times, click on the first FAQ link, test if the link RMK is present, click on login, test if forgot password link is present, enter my username and my password submit the form, get the profile page, test if My Profile link is present.
<?php
namespace RMK\SocialBundle\Tests\FunctionalTests\Controller\Website;
use RMK\SocialBundle\Controller\Website;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
class HomeControllerTest extends WebTestCase
{
public function testViewFAQ(){
$client = static::createClient();
$crawler = $client->request('GET', '/home');
$this->assertEquals(2, $crawler->filter('a:contains("FAQ")')->count());
$this->assertEquals(2, $crawler->filter('a:contains("FAQ")')->count());
$faqlink = $crawler->filter('a:contains("FAQ")')->eq(0)->link();
$crawler = $client->click($faqlink);
$this->assertEquals(1, $crawler->filter('a:contains("RMK")')->count());
$loginLink = $crawler->filter('a:contains("Login")')->eq(0)->link();
$crawler = $client->click($loginLink);
$this->assertEquals(1, $crawler->filter('a:contains("Forgot Password?")')->count());
$form = $crawler->selectButton('_submit')->form();
$form['_username'] = 'username';
$form['_password'] = 'test';
$crawler = $client->submit($form);
$crawler = $client->followRedirect();
$crawler = $client->request('GET', '/profile');
$this->assertEquals(1, $crawler->filter('a:contains("My Profile")')->count());
}
}
?>
The last assert failed by saying: Failed asserting that 0 matches expected 1. When I put var_dump(print_r($client->getResponse()->getContent())); just before this last assert I got this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=/home" />
<title>Redirecting to /home</title>
</head>
<body>
Redirecting to /home.
</body>
</html>bool(true)
I am sure I am missed something but I don't know what. Do you have an idea? Thx.
P.S: I am on Ubuntu 12.04.

Related

Call Solana web3.js from HTML

I am trying to run web3.js from HTML. Now so far I have been able to call window.solana.connect(); and window.solana.disconnect(); functions. However when I try run below code it doesn't work. I have tested it various options, like removing "web3." from the code but still didn't work. I would apprecaite if someone can guide me on how I can establish the connection.
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
Majority of my codes below is from the research done on Stackoveflow. Links below:
Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?
I would like to mint a new token on solana. How can I do this using solana-web3.js?
How can you transfer SOL using the web3.js sdk for Solana?
How to properly transfer Solana SOL using web3js via Phantom
Unfortunately docs on Phantom website don't help either. https://docs.phantom.app/integrating/establishing-a-connection
My existing codes below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Decentralized Ecommerce</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/3.0.0-rc.5/web3.min.js" integrity="sha512-jRzb6jM5wynT5UHyMW2+SD+yLsYPEU5uftImpzOcVTdu1J7VsynVmiuFTsitsoL5PJVQi+OtWbrpWq/I+kkF4Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{{ url_for('static', filename='app.js') }}"></script>
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"></script>
<script src="/static/solana.js"></script>
<script type="text/javascript">
async function transferSOL() {
//Changes are only here, in the beginning
if (window.solana.isConnected === false){
const resp = await window.solana.connect();
}
const pubKey = await window.solana.publicKey;
console.log("Public Key: ", pubKey);
// Establishing connection
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
alert('hello2');
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("4iSD5Q6AnyhRHu6Uz4u1KAzXh3TwNwwQshEGhZbEXUTw");
alert('hello3');
// Airdrop some SOL to the sender's wallet, so that it can handle the txn fee
var airdropSignature = await connection.requestAirdrop(
provider.publicKey,
web3.LAMPORTS_PER_SOL,
);
// Confirming that the airdrop went through
await connection.confirmTransaction(airdropSignature);
console.log("Airdropped");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: web3.LAMPORTS_PER_SOL //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Transaction constructor initialized successfully
if(transaction) {
console.log("Txn created successfully");
}
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
await connection.confirmTransaction(signature);
//Signature or the txn hash
console.log("Signature: ", signature);
}
</script>
</head>
After importing the script on the HTML:
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"> </script>
You should be able to call:
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl("mainnet-beta"));
Note it is solanaWeb3 not web3
Here is an example with Solana Web3 1.4:
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
Make sure to have installed the library via, npm install #solana/web3.js.

How to get a tensor from an image

I have an image and I would like to get the tensor from it.
Some of the images are already on the frontend server be whereas others will be served by the server
To do that, one needs to use fromPixels
In case the image is already displayed in an html page
You can consider doing a querySelector to get the image first and then you can use fromPixels
html
<img id="my-image" src="mydata.jpg">
js
const image = document.querySelector("#my-image")
const t = tf.fromPixels(image)
If the image is not present in the html page, you can use the constructor Image to create it and then pass it as parameter to fromPixels
const im = new Image()
im.onload = () => {
const a = tf.fromPixels(im, 4)
a.print()
console.log(a.shape)
}
im.src = "url-of-the-image"
document.body.appendChild(im)
onload makes sure that the image has finished downloading before converting it to a tensor.
If the image url and the url on which the frontend page is served are different there will be a cross-origin issue when creating the tensor. If the server serves the image with an access control that allows the frontend to retrieve that image, then setting the crossOrigin attribute of the image will solve the issue, otherwise there will nothing that can be done to get the tensor from that image.
const im = new Image()
im.crossOrigin = "anonymous";
im.src = "https://i.imgur.com/lVlPvCB.gif"
document.body.appendChild(im)
im.onload = () => {
const a = tf.fromPixels(im, 4)
a.print()
console.log(a.shape)
}
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
</head>
<body>
</body>
</html>

How - to launch print dialog when showing printable page in Oracle ADF

Hello I am developing an ADF Web application. In this I have test.jsf page and a showPrintablePage behaviour command button. When user click the button adf just shows a printable page in new window. But when the user clicks on the button it should directly show in print window of browser. For this I got the following code from ADF Code Corner.
public void beforePhaseMethod(PhaseEvent phaseEvent) {
if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
FacesContext fctx = FacesContext.getCurrentInstance();
AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
if (adfFacesContext.getOutputMode() == OutputMode.PRINTABLE) {
ExtendedRenderKitService erks = null;
erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
erks.addScript(fctx, "window.print();");
}
}
}
I have follwed the process specified in the document. And the follwoing is the test.jsf page code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page contentType="text/html;charset=UTF-8"%>
<%# taglib uri="http://xmlns.oracle.com/adf/faces/rich" prefix="af"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view beforePhase="#{viewScope.PieBean.beforePhaseMethod}">
<af:document title="printTest" id="d1">
<af:form id="f1">
<af:commandButton text="commandButton 1" id="cb1">
<af:showPrintablePageBehavior/>
</af:commandButton>
<af:goButton text="goButton 1" id="gb1"/>
</af:form>
</af:document>
</f:view>
but it is showing in test.jsf property inspector beforePhaseMethod is an unknown property.
And the final out is as follows
Please help.
Thanks in advance.
Did you register the bean in adfc-config or if you are using the taskflow, then in taskflow configuration. Also from the screenshot, it seems you are getting the desired output.

channel in trivial GAE app not getting 'onmessage'

I am trying to create the smallest possible GAE app to show the use of the channel api.
I have two handlers in the python, the first "TestPage" sends out the html shown below. The second "SendPage" tries to send a message over the channel to the test page. The code for the TestPage is
class TestPage(Handler):
def get(self):
token = channel.create_channel("1")
self.render("test.html", token = token)
It just creates the channel with an id of "1" and reders the page with the token passed back from create_channel().
The SendPage is just:
class SendPage(Handler):
def get(self):
channel.send_message("1", "hello")
self.write("sent hello to 1")
The html is as small as I could get it:
<!DOCTYPE HTML>
<html>
<body>
<br>Token is {{ token }}
<br>
<div id="debug">_</div>
<!--
<script src="https://talkgadget.google.com/talkgadget/channel.js"></script>
-->
<script src="static/channel.js"></script>
<script defer="defer">
function debug(s) {
document.getElementById("debug").innerHTML = s;
}
var channel = new goog.appengine.Channel( {{ token }} );
var socket = channel.open();
socket.onopen = function(e) {
debug("open");
}
socket.onclose = function(e) {
debug("close");
}
socket.onerror = function(e) {
debug("error");
}
socket.onmessage = function(e) {
debug("message");
}
debug("ready");
</script>
</body>
</html>
So, inside chrome I pull up TestPage and I see the "ready" message. Then I pull up the SendPage in another tab. And see the "sent message". Then when I go back to the TestPage I would expect to have "ready" replaced by "message". But this never happens. None of the socket handler functions are being called.
I'm stuck for the moment and would appreciate any help or suggestions.
Thank you.
Ok, I figured it out. There were two problems. First, the template line
var channel = new goog.appengine.Channel( {{ token }} );
should have been
var channel = new goog.appengine.Channel( "{{token}}" );
as it was token was something like "channel-2052893164-1373347311-1" which quietly evaluated to a number.
Second, the correct script for the channel.js was
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
The other scripts I had referenced were from other stack overflow answers and I guess they did not properly apply to this problem.
Thanks.

Why is current_user None?

I have a horrible bug that I put a bounty on and now I'm reducing to the simplest case of reproduction. At least a can reproduce it :D Some info: The entity FUser does not populate an entity, the javascript button switches between login / logout apprioriately and from the log you might be able to tell me what's wrong with the flow.
2011-10-04 17:34:14.398 /example 200 10ms 0cpu_ms 0kb Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0
213.89.134.0 - - [04/Oct/2011:13:34:14 -0700] "GET /example HTTP/1.1" 200 694 - "Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0" "www.koolbusiness.com" ms=11 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000157 instance=00c61b117c837db085d58acd70ffae167a06
D 2011-10-04 17:34:14.395
logging current_userNone
.py
"""A barebones AppEngine application that uses Facebook for login."""
FACEBOOK_APP_ID = "164355773607006"
FACEBOOK_APP_SECRET = "642f15e4324b45661e1049d5b139cb0"
import facebook
import os.path
import wsgiref.handlers
import logging
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
class FUser(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
class BaseHandler(webapp.RequestHandler):
"""Provides access to the active Facebook user in self.current_user
The property is lazy-loaded on first access, using the cookie saved
by the Facebook JavaScript SDK to determine the user ID of the active
user. See http://developers.facebook.com/docs/authentication/ for
more information.
"""
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
logging.debug("logging cookie"+str(cookie))
if cookie:
# Store a local instance of the user data so we don't need
# a round-trip to Facebook on every request
user = FUser.get_by_key_name(cookie["uid"])
logging.debug("user "+str(user))
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
user = FUser(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"])
user.put()
elif user.access_token != cookie["access_token"]:
user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
class HomeHandler(BaseHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "example.html")
logging.debug("logging current_user"+str(self.current_user))
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
self.response.out.write(template.render(path, args))
def main():
util.run_wsgi_app(webapp.WSGIApplication([(r"/example", HomeHandler)]))
if __name__ == "__main__":
main()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Facebook Example</title>
</head>
<body>
<fb:login-button autologoutlink="true"></fb:login-button>
{% if current_user %}
<p><img src="http://graph.facebook.com/{{ current_user.id }}/picture?type=square"/></p>
<p>Hello, {{ current_user.name|escape }}</p>
{% endif %}
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '{{ facebook_app_id }}', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('{% if current_user %}auth.logout{% else %}auth.login{% endif %}', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Update
I still don't get the user object and changed the HomeHandler to this
class HomeHandler(BaseHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), "example.html")
logging.debug("logging current_user"+str(self.current_user))
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
user = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
if not user:
logging.debug("no user")
if user:
graph = facebook.GraphAPI(user["access_token"])
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
logging.debug("logging profile"+str(profile))
self.response.out.write(template.render(path, args))
Relating to #Shay Erlichmen's observation, the above code shouldn't work due to facebook's changes of a few days ago. As I pointed out on your original question, there is a version of the facebook python SDK which has been modified to support the new authentication mechanism - see
https://gist.github.com/1190267
The specific place where this differs from the old version is in the get_user_from_cookie() method. If you're still using the old version of the facebook python SDK, this should look for an fbs_APPID cookie, not find it and return None - hence cookie is never assigned a value _current_user retains the None state assigned at the start of the method.
One check you can do is to have a look at the cookies in your browser - you should see the new fbsr_APPID cookies which are not handled by the old library.
Facebook switched to OAuth2.0 on October 1,2011, this code is old and should work anymore.

Resources