What is the use of test mode in Gin - go

I've checked the documentation but it does not explain the use of setting test mode for gin
gin.SetMode(gin.TestMode)
What is this test mode provided for? I do not see any difference when setting & not setting this mode in my tests.

The flag gin.DebugMode is used to control the output of gin.IsDebugging(), which adds some additional log output and changes the HTML renderer to the debug struct HTMLDebug.
The gin.TestMode is used in Gin's own unit tests to toggle the debug mode (and the additional logging) on and off, and the usage of the debug HTML renderer.
Other than that, it doesn't have other uses (source).
However, the flag can be controlled with the environment variable GIN_MODE=test. Then, since Mode() is exported, you can use it in application code to, for example, declare testing routes. This might have some merit if you plan to run an E2E test suite, or some other integration test:
r := gin.New()
if gin.Mode() == gin.TestMode {
r.GET("/test", func(c *gin.Context) {
c.String(418, "I don't exist in production")
})
}

Related

How to get WebStorm to run ESLint ruletester efficiently

I am writing an ESLint plugin and I have been testing with eslint.RuleTester. This is okay, I know how to configure their test options argument but I always have to run the entire test file.
here is an example test file:
const {RuleTester} = require('eslint');
const rulester = new RuleTester({setup});
const rule = require ('myrule');
//this works also but i have to run the entire file (and thus all the tests)
ruleTester.run('myruletest',rule,{invalid,valid});
Normally, when I install a test runner I get a run/configuration for it and handy play⏯ and debug🐞 buttons in line with each test. As I write more tests (particularly in the same file) it would be handy to quickly click a => beside a test and run just that single test.
If I try to call ruletester.run from a mocha.it callback it will not report the test correctly (and definitely cannot debug / step into it).
e.g. this does not work well
const mocha = require('mocha');
const {RuleTester} = require('eslint');
const rulester = new RuleTester({setup});
const rule = require ('myrule');
// nice play button and custom run configruation but not honest test feeback
it('mytest', ()=>{
// it'll run this but will not report correctly -- `it` says it always passes
ruleTester.run('myruletest, rule, {invalid,valid});
});
it('mytest', async ()=>{
// async is of no help
await ruleTester.run('myruletest, rule, {invalid,valid});
});
//this still works also but then i have to run the entire file (and thus all the tests)
ruleTester.run('myruletest',rule,{invalid,valid});
So how do I tell WebStorm to either
recognize eslint.RuleTester as a testrunner
properly call and instance of RuleTester from my own testrunner?
Recognizing eslint.RuleTester as a test runner would require developing a special plugin.
See http://www.jetbrains.org/intellij/sdk/docs/ for basic documentation on plugin development. You can use existing plugins as example: Mocha runner is not fully open source, but its JavaScript part is open source (https://github.com/JetBrains/mocha-intellij); also, there is an open source plugin for Karma https://github.com/JetBrains/intellij-plugins/tree/master/js-karma

Setting up Neo4J with Golang

I am setting up Go with Neo4j on a live project for one of the microservices
I went through the docs around setting up the same but it does not show the best practice to do the same (specifically globally and pass around the session instance throughout the application)
This is what I am doing to setup the same, was wondering if this is the right approach:
// app.go
import ""github.com/neo4j/neo4j-go-driver/neo4j""
type App struct {
Router *mux.Router
DB *sqlx.DB
Neo4j neo4j.Session // setting neo4j session globally for injection
}
// =============================
// Neo4j initialization
// =============================
driver, err2 := neo4j.NewDriver(
neo4jConfig.connstring,
neo4j.BasicAuth(neo4jConfig.username, neo4jConfig.password, ""),
func(c *neo4j.Config){
c.Encrypted = false
},
)
checkForErrors(err2, "Cannot connect to NEO4J")
defer driver.Close()
session, err3 := driver.NewSession(neo4j.SessionConfig{})
a.Neo4j = session // 👈 assigning the session instance
Now this will be injected as a dependency in the repo package where the queries are being executed
The example in the readme says the following:
// Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions
// per request in your web application. Make sure to call Close on the session when done.
// For multi-database support, set sessionConfig.DatabaseName to requested database
// Session config will default to write mode, if only reads are to be used configure session for
// read mode.
session := driver.NewSession(neo4j.SessionConfig{})
So having a global driver instance is not an issue, but you should not be using a global session instance since it is not thread safe.

Are there any config NOT to use trace on specific environment

Now I have a Golang Application deployed on GAE, with stackdriver trace.
About stackdriver Trace, to get custom span data, I did set up on my code, like
exporter, err := stackdriver.NewExporter(stackdriver.Options{
ProjectID: os.Getenv("GOOGLE_CLOUD_PROJECT"),
})
if err != nil {
log.Fatal(err)
}
trace.RegisterExporter(exporter)
client := &http.Client{
Transport: &ochttp.Transport{
// Use Google Cloud propagation format.
Propagation: &propagation.HTTPFormat{},
},
}
ref. https://cloud.google.com/trace/docs/setup/go
On GAE, I succeed in viewing trace on my GCP console.
but, I DON'T want to trace these log on my local developing environment (I'm using docker).currently, I try to run my application on docker, nil pointer panic shows up on Span.Export() which may be called from Span.End().
So, I wonder if someone knows the way to DISABLE stackdriver trace on specific environment (with my case, on docker).
Otherwise, should I check condition of trace configuration, like as below ?
if trace.projectId != "" {
ctx := reque.Context()
_, span := trace.StartSpan(ctx,"Span blahblah")
defer span.End()
}
There is no point for Google in adding an extra logic like you need into the Trace code, the GAE apps are instrumented with, in order to disable that Trace code when the GAE App is executed somewhere in a third party environment like Docker on-prem. Most likely an answer to the question is "No, there is no magic config for that". Hence it is up-to-you how to sort this out.
As a general idea: following up an approach with [NoopExporter] offered by Emile Pels and having admitted the fact we can't get rid of the Trace code with "magic config", if I developed my app in Python I'd considered using decorator as a wrapper to bring piece of intelligence into the Trace calls, or redefining them as mock functions. It seems Golang does not have direct analog of Python decorators but this functionality could be implemented somehow. This is being discussed in the Internet, for example here:
Go Decorator Function Pattern
Redefine function so that it references its own self

What is the difference between Zombie.js and Jasmine?

May I know what is the difference between Zombie.js and Jasmine? are they both frameworks?
Jasmine is a unit test framework for BDD (behavior driven development). It requires an execution environment like NodeJs or a browser like Firefox, Chrome, IE, PhantomJS etc. to run (and to provide the environment for the code under test). Jasmine provides the test execution and assertion infrastructure (that's the describe(), it(), expect()).
Zombie.js is an emulated, headless browser. It's a browser on its own plus an interaction API for itself. It's like Selenium/Webdriver. It's using jsdom under its hood to provide the APIs browsers usually provide. Zombie.js requires a test execution and assertion infrastructure (like Mocha + should.js or even Jasmine).
With Jasmine you write tests on a module or group-of-modules level. But usually not on an application level
With Zombie.js you interact with a website (served by a server) through an interaction API.
With Jasmine you make fine grained assertions on the output or events created for certain input - on the module level.
With Zombie.js you interact with the whole application (or website).
With Jasmine you test only the Javascript part.
With Zombie.js you test the the frontent + backend. Though you might be able to mock away and intercept server interaction (maybe, I'm not familar with it).
With Jasmine you call a method/function, pass a parameter and test the return value and events
With Zombie.js you load a page and fill a form and test the output
With Jasmine you need to run the tests in the proper execution envrionment (like Firefox, Chrome, ...)
With Zombie.js you pages runs in a new execution environment
With Jasmine you can test in browsers (consumers use) with their typical quirks
With Zombie.js you test you application in a new browser with new quirks
Jasmine example:
// spy on other module to know "method" was called on it
spyOn(otherModule, "method");
// create module
let module = new Module(otherModule),
returnValue;
// calls otherModule.method() with the passed value too; always returns 42
returnValue = module(31415);
// assert result and interaction with other modules
expect(returnValue).toBe(42);
expect(otherModule.method).toHaveBeenCalledWith(31415);
Zombie.js example:
// create browser
const browser = new Browser();
// load page by url
browser.visit('/signup', function() {
browser
// enter form data by name/CSS selectors
.fill('email', 'zombie#underworld.dead')
.fill('password', 'eat-the-living')
// interact, press a button
.pressButton('Sign Me Up!', done);
});
// actual test for output data
browser.assert.text('title', 'Welcome To Brains Depot');
Zombie.js, like Webdriver/Selenium, is no replacement for a unit testing framework like Jasmine, Mocha.

how to access Angular2 component specific data in console?

Is there any way to access Angular2 specific component specific data in console, for debugging purpose?
Like Angular1 has capability to access its components value in console.
update 4.0.0
StackBlitz example
update RC.1
Plunker example In the browser console on the top-left (filter symbol) select plunkerPreviewTarget (or launch the demo app in its own window) then enter for example
Select a component in the DOM node and execute in the console
ng.probe($0);
or for IE - thanks to Kris Hollenbeck (see comments)
ng.probe(document.getElementById('myComponentId')).componentInstance
Alternative
Hint: enabling debug tools overrides ng.probe()
Enable debug tools like:
import {enableDebugTools} from '#angular/platform-browser';
bootstrap(App, []).then(appRef => enableDebugTools(appRef))
Use above Plunker example and in the console execute for example:
ng.profiler.appRef
ng.profiler.appRef._rootComponents[0].instance
ng.profiler.appRef._rootComponents[0].hostView.internalView
ng.profiler.appRef._rootComponents[0].hostView.internalView.viewChildren[0].viewChildren
I haven't found a way yet to investigate the Bar directive.
A better debug experience is provided by Augury which builds on this API
https://augury.angular.io/
https://www.youtube.com/watch?v=b1YV9vJKXEA
original (beta)
Here is a summary how to do that https://github.com/angular/angular/blob/master/TOOLS_JS.md (dead link and I haven't found a replacement).
Enabling debug tools
By default the debug tools are disabled. You can enable debug tools as follows:
import {enableDebugTools} from 'angular2/platform/browser';
bootstrap(Application).then((appRef) => {
enableDebugTools(appRef);
});
Using debug tools
In the browser open the developer console (Ctrl + Shift + j in Chrome). The top level object is called ng and contains more specific tools inside it.
Example:
ng.profiler.timeChangeDetection();
See also
Angular 2: How enable debugging in angular2 from browser console
First select the element using chrome 'inspect element' and run below method in chrome 'developer console'.
ng.probe($0).componentInstance
You could also use a css selector as shown below.
ng.probe($$('.image-picker')[0]).componentInstance
If you do it often, to make it little easier, have a global shortcut created as below. Now select any DOM element inside the component using 'inspect element' and invoke 'e()' from console
window['e'] = () => eval('ng.probe($0).componentInstance');
Using global scope variable.(any browser)
In ngOnInit() of component file
ngOnInit() {
window['test'] = this;
}
Now we can access instance of that component including services(imported on that component).
If you want to prevent accessing test for let's say production, you can conditionally give access to test like:
constructor(private _configService: ConfigService) {
}
ngOnInit() {
if(_configService.prod) {
window['test'] = this;
}
}
Here _configService means the instance of service used by all components and services.
So variable would be set like:
export class ConfigService {
prod = false;
}
I'm surprised that no one has mentioned Augury here, it's a Chrome plugin that gives you convenient access to all the information in your components, and also makes it easier to see that information in the console directly:
https://augury.rangle.io/
Angular 9+:
Select component root element in developer tools (Inspector), then type in console:
ng.getComponent($0);

Resources