Saturday, February 20, 2021

how to fix "Error from server (BadRequest): container "nodeapp" in pod "nodeapp" is waiting to start: trying and failing to pull image"?

 if you try to run the image from AKR(Azure Kubernetes Registry) with the following command in the Azure CLI

 kubectl run nodeapp \

  --image=mydanaksacr.azurecr.io/node:v1 \

  --port=8080

the output indicate that the pod was create. however when you check the pod. the result is below

danny@Azure:~/clouddrive$ kubectl get pods

NAME      READY   STATUS         RESTARTS   AGE

nodeapp   0/1     ErrImagePull   0          36s


after I check the log with kubectl logs on the pod 

danny@Azure:~/clouddrive$ kubectl logs nodeapp

Error from server (BadRequest): container "nodeapp" in pod "nodeapp" is waiting to start: image can't be pulled

the message indicates that the service principal does not have the right to pull the image from AKR

here is the solution to solve the issue. run the following command in the cli to grant the service principal to the acrpull role.

az role assignment create --assignee "<<service principal ID>>" --role acrpull --scope "<<AKR resource ID>>"

this is the specific example running in the development environment

 az role assignment create --assignee "34d6880e-bc51-416f-b250-b87904390d0c" --role acrpull --scope "/subscriptions/3f2c3687-9d93-45be-a8e0-b8ca6e4f5944/resourceGroups/MyResourceGroup/providers/Microsoft.ContainerRegistry/registries/myDanAksAcr"



Monday, February 1, 2021

how to fix " ReferenceError: fetch is not defined" in redux testing with nock and jest?

when i implemented a test a case against the API call to test the reducer, we can use NOCK to mock the API with JEST test run.

here is the sample code for the above test case.

import { createStoreapplyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import nock from 'nock'

import { fetchUser } from '../../src/actions'
import usersReducer from '../../src/reducers/users'

// global.fetch = require('node-fetch');
const middlewares = [ thunk ]
let store

beforeEach(() => {
  store = createStore(usersReducerapplyMiddleware(thunk))
})

afterEach(() => {
  nock.cleanAll()
})

test('initial state should be empty array (no users)', () => {
  expect(store.getState()).toEqual([])
})

test('fetchUser action should add user object to state', () => {
  const username = 'dan'
  const realname = 'Dan Deng'
  const userObj = { username:usernamerealname:realname }
  console.log(userObj)
  nock('http://localhost:8080/')
    .get(`/api/users/${username}`)
    .reply(200userObj)

  expect.assertions(1)

  const action = fetchUser(username)
  return store.dispatch(action)
    .then(() =>
      expect(store.getState()).toContainEqual(userObj)
    )
})


however i ran the test case with JEST, the following error came immediately. since i use fetch function from fetch-node module.

 ● fetchUser action should add user object to state

    ReferenceError: fetch is not defined

      23 |     types:[FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE],
      24 |     promise: fetch(`http://localhost:8080/api/users/${username}`)
    > 25 |     .then(response=>response.json())
         |      ^
      26 | })
      27 |
      28 | export const createUser=(username, realname, password)=>thunkCreator({

      at fetchUser (src/actions/users.js:25:6)
      at Object.<anonymous> (_test_/reducers/users.test.js:88:18)

  ● fetchUser action should add user object to state

    expect.assertions(1)

    Expected one assertion to be called but received zero assertion calls.

      84 |     .reply(200, userObj)
      85 |
    > 86 |   expect.assertions(1)
         |          ^
      87 |
      88 |   const action = fetchUser(username)
      89 |   return store.dispatch(action)

      at Object.<anonymous> (_test_/reducers/users.test.js:86:10)


the fix is very easy, we just have to add the reference to fetch in the test file. the test case was passed and succeed.

 global.fetch = require('node-fetch');


Sunday, January 31, 2021

how to use test object array contain element which match giving object?

 when we write a test case to verify that an object array contains specific object within JEST framework

we can use the following code to handle it .

let posts=[]

beforeAll(()=>{
    posts.push({title:'test'user:'dan'})
    posts.push({title:'hello world'user:'dan'})
})

test('test post exists',()=>{
    expect(posts).toEqual(
        expect.arrayContaining([
            expect.objectContaining({title: 'test'})
        ])
    )
})

Sunday, January 17, 2021

how to quickly fix "future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed "javascript:void(0)"

 when we implement a click event to trigger api call or dispatch an action in redux, we will like to use this simple syntax to handle it.

<a href="javascript:void(0)" onClick={clearFilter}>all posts</a>

we will see the following warming in the development tool windows


since React 16.9 update had deprecate the JavaScript URL, you can check out this link for more information

https://reactjs.org/blog/2019/08/08/react-v16.9.0.html

but the work around is quiet simple. we can fix it withe code below.

<a href="#" onClick={ev => {
            ev.preventDefault();
           clearFilter
            return false; // old browsers, may not be needed
            }}>all posts</a>


 








Saturday, December 5, 2020

use This keyword with Arrow Function in Javascript implementation

 when we write JavaScript function with Arrow to eliminate the function key, we must be extra caution, since THIS keyword object reference will be determine during the runtime, if the function is in the global scope, then THIS will point to the window object. if the function is pointing within the object, then THIS will only point to the object itself.

here is a simple example.

print: (delay=3000)=> {
    setTimeout(() => {
    console.log(this === window)
    }, delay)
}

the output is true. since THIS is execute with under the global scope.


after I change the Arrow function to a regular function, then  THIS key is reference to the object level

function print(delay=3000){
    setTimeout(() => {
    console.log(this === window)
    }, delay)
}

though arrow function is very handy in the javascript implementation, but we still have use it with care.




Friday, December 4, 2020

how to launch a program with Run as Administrator privilege in powershell?

 when you in the powershell window, you want to launch another app with run as administrator right. here is a way to go

ex: launch powershell with administrator privilege

start-process powershell  --Verb  runas

 run visual studio with administrator privilege

  start-process devenv.exe --Verb  runas



Thursday, August 13, 2020

How to add gwin to windows CMD or cmder?

it is very useful to use vi editor to compose yaml file for Kubernetes. we can launch the VI or VIM editor by typing vi or vim in the CMD or cmder.

 if you are not comfortable working with vi or vim. there is GUI version of vi call gwin.

you can download a copy of gwin for windows from the link below.

 https://www.vim.org/download.php#pc

1.  you should run the exe file with administrator privilege to ensure the file can install into the proper location.

2. second step you can either run this script in the powershell window

 Set-alias gvim "C:\Program Files (x86)\Vim\vim82\gvim.exe"

or add the application path (C:\Program Files (x86)\Vim\vim82\gvim.exe) to the Path variable in the Environment Variable Window

 

 

then you can launch gwin editor from CMD or cmder