Tumgik
codehunter · 9 months
Text
Jest: How to correctly mock a node module?
I want to mock the node_module 'React Native Keychain' in React Native with Jest.
Following the docs I created a folder called __mocks__ and created a file called react-native-keychain.js in it.
Here is the code within the file:
export default jest.mock("react-native-keychain", () => { const token = "abcdefghijklmnopqrstuvwxyz0123456789"; const credentials = { username: "session", password: token }; return { setGenericPassword: jest.fn( (username, password) => new Promise((resolve, reject) => resolve(true)) // eslint-disable-line no-unused-vars ), getGenericPassword: jest.fn(() => new Promise((resolve, reject) => resolve(credentials))), // eslint-disable-line no-unused-vars resetGenericPassword: jest.fn(() => new Promise((resolve, reject) => resolve(true))) // eslint-disable-line no-unused-vars };});
I then wrote my tests for the functions that use this library:
import * as keyChainFunctions from "react-native-keychain";import { setToken, getToken, clearToken } from "./secureStorage";const token = "abcdefghijklmnopqrstuvwxyz0123456789"; describe("set token", () => { it("saves the token in the keychain", () => { expect.assertions(1); return setToken(token).then(res => { console.log(res); console.log(keyChainFunctions); expect(keyChainFunctions.setGenericPassword).toHaveBeenCalledWith("session", token); }); }); });
The problem is, that the test fails. I get the error message:
FAIL app/api/secureStorage/secureStorage.test.js set token ✕ saves the token in the keychain (42ms) ● set token › saves the token in the keychain expect(jest.fn())[.not].toHaveBeenCalledWith() jest.fn() value must be a mock function or spy. Received: undefined 10 | console.log(res); 11 | console.log(keyChainFunctions); > 12 | expect(keyChainFunctions.setGenericPassword).toHaveBeenCalledWith("session", token); | ^ 13 | }); 14 | }); 15 | }); at app/api/secureStorage/secureStorage.test.js:12:52 at tryCallOne (node_modules/promise/lib/core.js:37:12) at node_modules/promise/lib/core.js:123:15 at flush (node_modules/asap/raw.js:50:29) ● set token › saves the token in the keychain expect.assertions(1) Expected one assertion to be called but received zero assertion calls. 6 | describe("set token", () => { 7 | it("saves the token in the keychain", () => { > 8 | expect.assertions(1); | ^ 9 | return setToken(token).then(res => { 10 | console.log(res); 11 | console.log(keyChainFunctions); at Object.<anonymous> (app/api/secureStorage/secureStorage.test.js:8:12)
And the console.log() yield:
console.log app/api/secureStorage/secureStorage.test.js:10 true console.log app/api/secureStorage/secureStorage.test.js:11 { default: { addMatchers: [Function: addMatchers], advanceTimersByTime: [Function: advanceTimersByTime], autoMockOff: [Function: disableAutomock], autoMockOn: [Function: enableAutomock], clearAllMocks: [Function: clearAllMocks], clearAllTimers: [Function: clearAllTimers], deepUnmock: [Function: deepUnmock], disableAutomock: [Function: disableAutomock], doMock: [Function: mock], dontMock: [Function: unmock], enableAutomock: [Function: enableAutomock], fn: [Function: bound fn], genMockFromModule: [Function: genMockFromModule], isMockFunction: [Function: isMockFunction], mock: [Function: mock], requireActual: [Function: bound requireModule], requireMock: [Function: bound requireMock], resetAllMocks: [Function: resetAllMocks], resetModuleRegistry: [Function: resetModules], resetModules: [Function: resetModules], restoreAllMocks: [Function: restoreAllMocks], retryTimes: [Function: retryTimes], runAllImmediates: [Function: runAllImmediates], runAllTicks: [Function: runAllTicks], runAllTimers: [Function: runAllTimers], runOnlyPendingTimers: [Function: runOnlyPendingTimers], runTimersToTime: [Function: runTimersToTime], setMock: [Function: setMock], setTimeout: [Function: setTimeout], spyOn: [Function: bound spyOn], unmock: [Function: unmock], useFakeTimers: [Function: useFakeTimers], useRealTimers: [Function: useRealTimers] } }
What this tells me: 1. Either the mock works (because true is returned correctly) or the actual setGenericPassword function from React Native Keychain is being called. 2. For some reason, keychainfunctions is defined, but as the jest.mock object instead of the three mocked functions.
It feels like 1 and 2 contradict each other, if the mock works.What am I doing wrong? Why does this mock not work? How can these weird console.log()s and failed tests be explained?
Bamse suggested in the comments to just export objects. This workaround works. I would still be interested how to correctly do it / what I did wrong.
const token = "abcdefghijklmnopqrstuvwxyz0123456789";const credentials = { username: "session", password: token};export const setGenericPassword = jest.fn( (username, password) => new Promise((resolve, reject) => resolve(true)) // eslint-disable-line no-unused-vars);export const getGenericPassword = jest.fn( () => new Promise((resolve, reject) => resolve(credentials)) // eslint-disable-line no-unused-vars);export const resetGenericPassword = jest.fn(() => new Promise((resolve, reject) => resolve(true))); // eslint-disable-line no-unused-vars
https://codehunter.cc/a/reactjs/jest-how-to-correctly-mock-a-node-module
0 notes
codehunter · 9 months
Text
Seedable JavaScript random number generator
The JavaScript Math.random() function returns a random value between 0 and 1, automatically seeded based on the current time (similar to Java I believe). However, I don't think there's any way to set you own seed for it.
How can I make a random number generator that I can provide my own seed value for, so that I can have it produce a repeatable sequence of (pseudo)random numbers?
https://codehunter.cc/a/javascript/seedable-javascript-random-number-generator
0 notes
codehunter · 9 months
Text
Storing oAuth state token in Flask session
A couple of tutorials on oAuth use the Flask session to store state parameters and access tokens in the flask session. (Brendan McCollam's very useful presentation from Pycon is an example)
I understand that Flask stores the session in cookies on the client side and that they are fairly easy to expose (see Michael Grinberg's how-secure-is-the-flask-user-session). I tried this myself and was able to see the token the expiration, etc.
Is it correct to store the state and tokens in the flask session or they should be stored somewhere else?
Code example:
@app.route('/login', methods=['GET'])def login(): provider = OAuth2Session( client_id=CONFIG['client_id'], scope=CONFIG['scope'], redirect_uri=CONFIG['redirect_uri']) url, state = provider.authorization_url(CONFIG['auth_url']) session['oauth2_state'] = state return redirect(url)@app.route('/callback', methods=['GET'])def callback(): provider = OAuth2Session(CONFIG['client_id'], redirect_uri=CONFIG['redirect_uri'], state=session['oauth2_state']) token_response = provider.fetch_token( token_url=CONFIG['token_url'], client_secret=CONFIG['client_secret'], authorization_response=request.url) session['access_token'] = token_response['access_token'] session['access_token_expires'] = token_response['expires_at'] transfers = provider.get('https://transfer.api.globusonline.org/v0.10/task_list?limit=1') return redirect(url_for('index'))@app.route('/')def index(): if 'access_token' not in session: return redirect(url_for('login')) transfers = requests.get('https://transfer.api.globusonline.org/v0.10/task_list?limit=1', headers={'Authorization': 'Bearer ' + session['access_token']}) return render_template('index.html.jinja2', transfers=transfers.json())
https://codehunter.cc/a/flask/storing-oauth-state-token-in-flask-session
0 notes
codehunter · 9 months
Text
Simple DataTables flask
I have no experience in web development, and I would like to add data for a table of specified fields with flask, this is my app
from flask import *from flask import jsonifyapp = Flask(__name__)@app.route('/page_test') def page_test(): meas = {"MeanCurrent": 0.05933, "Temperature": 15.095, "YawAngle": 0.0, "MeanVoltage": 0.67367, "VoltageDC": 3.18309, "PowerSec": 0.06923, "FurlingAngle": -0.2266828184, "WindSpeed": 1.884, "VapourPressure": 1649.25948, "Humidity": 0.4266, "WindSector": 0, "AirDensity": 1.23051, "BarPressure": 1020.259, "time": "2015-04-22 20:58:28", "RPM": 0.0, "ID": 1357} return jsonify(meas)if __name__ == "__main__": app.run(debug=True)
and this is my html (templates/view.html)
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-1.12.4.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script><script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js"></script><script type="text/javascript" charset="utf8" src="https://editor.datatables.net/extensions/Editor/js/dataTables.editor.min.js"></script><table id="myTable" class="table table-striped" style="width:100%" > <thead> <tr> <th>Time</th> <th>Mean Current</th> <th>Vapour Pressure</th> <th>Mean Voltage</th> <th>Temperature</th> <th>Humidity</th> <th>Bar Pressure</th> <th>RPM</th> <th>Wind Sector</th> <th>Wind Speed</th> <th>Air Density</th> <th>DC Voltage</th> <th>Power Sector</th> <th>Furling Angle</th> <th>Yaw angle</th> </tr> </thead> </table> <script>$(document).ready(function() { $('#myTable').DataTable( { "processing": true, "ajax": "/page_test", // add column definitions to map your json to the table "columns": [ {data: "time"}, {data: "MeanCurrent"}, {data: "VapourPressure"}, {data: "MeanVoltage"}, {data: "Temperature"}, {data: "Humidity"}, {data: "BarPressure"}, {data: "RPM"}, {data: "WindSector"}, {data: "AirDensity"}, {data: "VoltageDC"}, {data: "PowerSec"}, {data: "FurlingAngle"}, {data: "YawAngle"} ] } );});</script>
accessing the url http://127.0.0.1:5000/page_test only have the json file is displayed.
How can I make the script read the data and display the table?
https://codehunter.cc/a/flask/simple-datatables-flask
0 notes
codehunter · 9 months
Text
How does Bluebird's util.toFastProperties function make an object's properties "fast"?
In Bluebird's util.js file, it has the following function:
function toFastProperties(obj) { /*jshint -W027*/ function f() {} f.prototype = obj; ASSERT("%HasFastProperties", true, obj); return f; eval(obj);}
For some reason, there's a statement after the return function, which I'm not sure why it's there.
As well, it seems that it is deliberate, as the author had silenced the JSHint warning about this:
Unreachable 'eval' after 'return'. (W027)
What exactly does this function do? Does util.toFastProperties really make an object's properties "faster"?
I've searched through Bluebird's GitHub repository for any comments in the source code or an explanation in their list of issues, but I couldn't find any.
https://codehunter.cc/a/javascript/how-does-bluebirds-util-tofastproperties-function-make-an-objects-properties-fast
0 notes
codehunter · 9 months
Text
Using react-router and express with authentication via Passport.js - possible?
So I'm working on a project that incorporates React, Express.js+Passport and Webpack. I understand the concept of pushing everything to a 'master' React component via react-router, then letting it hash out what gets displayed for the given route. That would work great here, I think. To be upfront, I am new to React.
My concerns are:
1) Can I/how can I still use Passport to authenticate my routes? If I understand react-router correctly, I'll have one route in my express app.js file, pointing to, say, a React component named <Application/>. However, Passport needs router.get('/myroute', isAuthenticated, callback) to check the session. Is it still possible to do so with react-router?
2) Furthermore, if this is possible, how do I pass values from the route in Express into my views, in React? I know in a typical view, I could use <%= user %> or {{user}} if I passed that from my route. Is that possible here?
https://codehunter.cc/a/reactjs/using-react-router-and-express-with-authentication-via-passport-js-possible
0 notes
codehunter · 9 months
Text
How to Handle Refresh Token When Multiple Requests are going out?
I am using reactjs, mbox and axios and ran into a problem. I have a api that gives out an access token and a refresh token. The access token dies every 20mins and when this happens the server sends a 401 back and my code will automatically send the refresh token out to get a new access token.
Once a new access token is granted that same rejected request will be sent again. Now my code works great until I throw multiple rejects that pretty much could fire all at the same time.
So first request goes off, a 401 is sent back and it gets a new refresh token, well all the other requests will be trying to do the same thing but the other requests will now fail because the refresh token will be used and a new one will be issued to the first request.
This will kick off my code to redirect the user to the login page.
So essentially I am stuck of only have 1 request at a time.
export const axiosInstance = axios.create({ baseURL: getBaseUrl(), timeout: 5000, contentType: "application/json", Authorization: getAuthToken() }); export function updateAuthInstant() { axiosInstance.defaults.headers.common["Authorization"] = getAuthToken(); }function getAuthToken() { if (localStorage.getItem("authentication")) { const auth = JSON.parse(localStorage.getItem("authentication")); return `Bearer ${auth.accessToken}`; } }axiosInstance.interceptors.response.use( function(response) { return response; }, function(error) { const originalRequest = error.config; if (error.code != "ECONNABORTED" && error.response.status === 401) { if (!originalRequest._retry) { originalRequest._retry = true; return axiosInstance .post("/tokens/auth", { refreshToken: getRefreshToken(), grantType: "refresh_token", clientId : "myclient" }) .then(response => { uiStores.authenticaionUiStore.setAuthentication(JSON.stringify(response.data)) updateAuthInstant(); return axiosInstance(originalRequest); }); } else { uiStores.authenticaionUiStore.logout(); browserHistory.push({ pathname: '/login',}); } } return Promise.reject(error); });
Edit
I am having problem that the code I Need to check to resetup authentication is not working when a user copies in a direct url
app.js
<React.Fragment> <Switch> <Route path="/members" component={MemberAreaComponent} /> </Switch> </React.Fragment >
In memberAreaComponent
<Route path="/members/home" component={MembersHomeComponent} />
When I type in http://www.mywebsite/members/home
MembersHomeComponent - componentDidMount runs firstMemberAreaComponent - componentDidMount runs secondAppCoontainer = componentDidMount runs last.
https://codehunter.cc/a/reactjs/how-to-handle-refresh-token-when-multiple-requests-are-going-out
0 notes
codehunter · 9 months
Text
How to unnest (explode) a column in a pandas DataFrame?
I have the following DataFrame where one of the columns is an object (list type cell):
df=pd.DataFrame({'A':[1,2],'B':[[1,2],[1,2]]})dfOut[458]: A B0 1 [1, 2]1 2 [1, 2]
My expected output is:
A B0 1 11 1 23 2 14 2 2
What should I do to achieve this?
Related question
pandas: When cell contents are lists, create a row for each element in the list
Good question and answer but only handle one column with list(In my answer the self-def function will work for multiple columns, also the accepted answer is use the most time consuming apply , which is not recommended, check more info When should I ever want to use pandas apply() in my code?)
https://codehunter.cc/a/python/how-to-unnest-explode-a-column-in-a-pandas-dataframe
0 notes
codehunter · 9 months
Text
Controlling fps with requestAnimationFrame?
It seems like requestAnimationFrame is the de facto way to animate things now. It worked pretty well for me for the most part, but right now I'm trying to do some canvas animations and I was wondering: Is there any way to make sure it runs at a certain fps? I understand that the purpose of rAF is for consistently smooth animations, and I might run the risk of making my animation choppy, but right now it seems to run at drastically different speeds pretty arbitrarily, and I'm wondering if there's a way to combat that somehow.
I'd use setInterval but I want the optimizations that rAF offers (especially automatically stopping when the tab is in focus).
In case someone wants to look at my code, it's pretty much:
animateFlash: function() { ctx_fg.clearRect(0,0,canvasWidth,canvasHeight); ctx_fg.fillStyle = 'rgba(177,39,116,1)'; ctx_fg.strokeStyle = 'none'; ctx_fg.beginPath(); for(var i in nodes) { nodes[i].drawFlash(); } ctx_fg.fill(); ctx_fg.closePath(); var instance = this; var rafID = requestAnimationFrame(function(){ instance.animateFlash(); }) var unfinishedNodes = nodes.filter(function(elem){ return elem.timer < timerMax; }); if(unfinishedNodes.length === 0) { console.log("done"); cancelAnimationFrame(rafID); instance.animate(); }}
Where Node.drawFlash() is just some code that determines radius based off a counter variable and then draws a circle.
https://codehunter.cc/a/javascript/controlling-fps-with-requestanimationframe
0 notes
codehunter · 9 months
Text
Nesting a container component in a presentational component
I'm trying to refactor my app to separate presentational and container components. My container components are just the presentational components wrapped in connect() calls from react-redux, which map state and action creators to the presentational components' props.
todo-list.container.js
import React, {Component} from 'react';import {connect} from 'react-redux';import {fetchTodos} from '../actions/todo.actions';import TodoList from '../components/todo-list.component';export default connect(({todo}) => ({state: {todo}}), {fetchTodos})(TodoList);
todo-list.component.jsx
import React, {Component} from 'react';import TodoContainer from '../containers/todo.container';export default class TodoList extends Component { componentDidMount () { this.props.fetchTodos(); } render () { const todoState = this.props.state.todo; return ( <ul className="list-unstyled todo-list"> {todoState.order.map(id => { const todo = todoState.todos[id]; return <li key={todo.id}><TodoContainer todo={todo} /></li>; })} </ul> ); }};
todo.container.js
import React, {Component} from 'react';import {connect} from 'react-redux';import {createTodo, updateTodo, deleteTodo} from '../actions/todo.actions';import Todo from '../components/todo.component';export default connect(null, {createTodo, updateTodo, deleteTodo})(Todo);
todo.component.jsx
import React, {Component} from 'react';import '../styles/todo.component.css';export default class Todo extends Component { render () { return ( <div className="todo"> {todo.description} </div> ); }};
What I'm trying to figure out is this: I know I should not be embedding the <TodoContainer /> element inside of TodoList because TodoList is a presentational component and it should only nest other presentational components inside of it. But if I replace it with just a <Todo /> presentational component, then I have to map every state prop and action creator prop in TodoListContainer that the Todo component would need and pass them all down the chain manually as props. This is something I want to avoid of course, especially if I start nesting more levels or start depending on more props coming from Redux.
Am I approaching this correctly? It seems that I shouldn't be trying to embed a container component inside of a presentational component in general, because if I can decouple presentational components from Redux, they become more reusable. At the same time, I don't know how else to embed a component that requires access to Redux state/dispatch inside of any other component that has markup.
https://codehunter.cc/a/reactjs/nesting-a-container-component-in-a-presentational-component
0 notes
codehunter · 9 months
Text
Django: check whether an object already exists before adding
How do I check whether an object already exists, and only add it if it does not already exist?
Here's the code - I don't want to add the follow_role twice in the database if it already exists. How do I check first? Use get() maybe - but then will Django complain if get() doesn't return anything?
current_user = request.userfollow_role = UserToUserRole(from_user=current_user, to_user=user, role='follow')follow_role.save()
https://codehunter.cc/a/django/django-check-whether-an-object-already-exists-before-adding
0 notes
codehunter · 9 months
Text
Django model naming convention
What is the preferred naming convention for Django model classes?
https://codehunter.cc/a/django/django-model-naming-convention
0 notes
codehunter · 9 months
Text
Adding resources with jwt_required?
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.
However if I add a resource that has a jwt_required decorator I get this error.
File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])KeyError: 'JWT_DEFAULT_REALM'
Example resource:
class Endpoint(Resource): @jwt_required() def get(self): return {"State": "Success"}
Initialising the app:
app = Flask(__name__)api = Api(app)
Adding the resource:
api.add_resource(resource_class, "/myEndpoint")
The only way I can get it to work is to define the Endpoint class in the same file as the API.
I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.
https://codehunter.cc/a/flask/adding-resources-with-jwt-required
0 notes
codehunter · 9 months
Text
How to create list field in django
How do I create a ListField in Django (Python) like the ListProperty property in Google App Engine (Python)? My data is a list like this : 3,4,5,6,7,8.
What property do I have to define and how would I fetch values from it?
https://codehunter.cc/a/django/how-to-create-list-field-in-django
0 notes
codehunter · 9 months
Text
How to change the Content of a <textarea> with JavaScript
How would I change the content of a <textarea> element with JavaScript?
I want to make it empty.
https://codehunter.cc/a/javascript/how-to-change-the-content-of-a-textarea-with-javascript
0 notes
codehunter · 9 months
Text
Django bulk_create function example
I'm trying to understand bulk_create in Django
This was my original query I'm trying to convert:
for e in q: msg = Message.objects.create( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, billee=batch.user, sender_name=batch.sender_name )
Does that mean doing the following (below) will loop and create all the entries first then hit the database? Is this right?
msg = Message.objects.bulk_create({ Message ( recipient_number=e.mobile, content=batch.content, sender=e.contact_owner, billee=batch.user, sender_name=batch.sender_name ),})
https://codehunter.cc/a/django/django-bulk-create-function-example
0 notes
codehunter · 9 months
Text
Zoom in on a point (using scale and translate)
I want to be able to zoom in on the point under the mouse in an HTML 5 canvas, like zooming on Google Maps. How can I achieve that?
https://codehunter.cc/a/javascript/zoom-in-on-a-point-using-scale-and-translate
0 notes