What's C++'s `using` equivalent in golang - c++

What's C++'s using some_namespace::object equivalent in golang?
According to the question here
I can get using namespace common with statement below:
import (
. "common"
)
But this would import the entire namespace. Right now I only want to use, say platform definition, something like using common::platform
Is there an equivalent for this in Go, so that I don't have to type common.platform all the time?

The following code comes close in terms of readability, but is less efficient, since the compiler cannot inline function calls anymore.
import (
"fmt"
"strings"
)
var (
Sprintf = fmt.Sprintf
HasPrefix = strings.HasPrefix
)
And, it has the side-effect of importing the names fmt and strings into the file scope, which is something that C++'s using does not do.

There is currently no such functionality in Go.
That's not to say it will never be added: there is open proposal to add "Alias declarations" to the language.

As others said, it is not possible in Go. In Go you import packages, not functions or types from packages.
Note that you can easily achieve what you want if you create a helper package.
Let's say you want "using" the fmt.Println() and fmt.Printf() functions only. Create a helper package:
package helper
import "fmt"
func Println(a ...interface{}) (n int, err error) {
return fmt.Println(a...)
}
func Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Printf(format, a...)
}
And where you want the C++'s "using" functionality, import using a dot .:
import . "helper"
func Something() {
Println("Hi")
Printf("Using format string: %d", 3)
}
The result is that only the exported identifiers of the helper package will be in scope, nothing else from the fmt package. You can use this single helper package to make functions available from packages other than fmt of course, too. helper can import any other packages and have a "proxy" or delegator function publishing their functionality.
Personally I don't feel the need of this. I would just import fmt and call its functions using fmt.Println() and fmt.Printf().

Perhaps you could rename the package:
import (
c "common"
cout2 "github.com/one/cout"
cout2 "github.com/two/cout"
)
Then you would only have to type c.Platform

Related

How to create library for v lang by c++

I would like to ask how to create a module on c++ for v lang.
For example
с++
int some_method() {
return 6
}
v
import my_c_module
my_c_module.some_method()
I will be grateful for any information
And can I call c++ class method in v lang?
In V every file in the root of a folder is part of the same module. Simple programs don't need to specify module name, in which case it defaults to 'main'.
V is a very modular language. Creating reusable modules is encouraged and is quite easy to do. To create a new module, create a directory with your module's name containing .v files with code:
cd ~/code/modules
mkdir mymodule
vim mymodule/myfile.v
Inside myfile.v
// myfile.v
module mymodule
// To export a function we have to use `pub`
pub fn say_hi() {
println('hello from mymodule!')
}
Now you can call your module
import mymodule
fn main() {
mymodule.say_hi()
}
You can create also your custom module, and here is the official docs

AWS Lambda with aws-sdk-go-v2

I migrated aws-sdk-go-v2 to v0.31.0 from v0.25.0.
My code is a bit of a Frankenstein's Monster and I want to fully migrate to this version but I can't find the current location/approach for some features.
Specifically:
I had:
func HandleRequest(ctx context.Context, event events.APIGatewayV2HTTPRequest) (string, error) {}
The relevant import was "github.com/aws/aws-lambda-go/events". I had a rake around various service but can't locate an update, is that still correct?
Also func main() used to be:
func main() {
lambda.Start(HandleRequest)}
But no more Start() method, so what is the correct paradigm now ?
The sdk is a lot better, but I am missing the examples.
Are you importing both github.com/aws/aws-lambda-go/lambda and github.com/aws/aws-sdk-go-v2/service/lambda? If so, try importing the former with:
runtime "github.com/aws/aws-lambda-go/lambda"
And then call runtime.Start(HandleRequest)
As for handling events, see the samples in https://github.com/aws/aws-lambda-go/tree/master/events.

Mock not being called in Jest

Please help me understand Jest mocks.
I've put some dummy functions in a file:
// actions.js
export function f1() {
return 1
}
export function calls_f1() {
f1()
}
And then in my test file I'm trying to understand how to check that a function calls another function:
import * as actions from './actions.js'
describe("MOCKS", () => {
actions.f1 = jest.fn();
actions.calls_f1();
expect(actions.f1).toBeCalled();
});
But the test is failing saying the mock function wasn't called. I've also tried swapping the 2nd and 3rd lines of the test, to no avail.
My jest config is all good, I've actually been doing a bunch of other testing (in this same file) that works.
What am I missing here?
Note: The actual implementation of this (that I'm simplifying greatly here) involves an actions file that includes a public export function fetchStations() that calls a private (or, rather, not exported) export function _downloadStations(). I'm trying to test that _downloadStations() is called.
I'm using import * as actions only for convenience, so I can write that line and then use whatever functions that file exports under actions.whatever() (instead of having to add functions to the import statement when I decide to use them). If import * as actions has some effect I'm not noticing (as implied by brian below) then I certainly don't have to use it and can use import {thisAction, thatAction} from './actions' of course.
This line:
import * as actions from './actions.js'
binds the module exports from actions.js to actions...
...so setting actions.f1 to a mock function replaces the module export for f1...
...but this doesn't affect calls_f1 since it calls f1 directly.
If calls_f1 is changed to call the module export for f1 then it will call the mock function.
There are two ways to make that happen.
One way is to move f1 into its own module.
The other way is to note that ES6 modules "support cyclic dependencies automatically" (a major design goal of ES6 modules) so a module can import its own exports:
actions.js
import * as actions from './actions'; // <= import the module...
export function f1() {
return 1
}
export function calls_f1() {
actions.f1() // <= ...and use it to call f1
}
actions.test.js
import * as actions from './actions.js'
describe('actions', () => {
it('calls_f1 should call f1', () => {
actions.f1 = jest.fn();
actions.calls_f1();
expect(actions.f1).toBeCalled(); // Success!
})
})
Update
OP updated the question to indicate that the function in question is not exported from the module.
In that case it is just an internal implementation detail of the module and cannot be spied on directly.
Testing it would involve testing for the effects that it causes, and not directly spying on it to see if it was called.

Is it possible to mock a function imported from a package?

I have the following method to test, which uses a function imported from a package.
import x.y.z
func abc() {
...
v := z.SomeFunc()
...
}
Is it possible to mock SomeFunc() in Go?
Yes, with a simple refactoring. Create a zSomeFunc variable of function type, initialized with z.SomeFunc, and have your package call that instead of z.SomeFunc():
var zSomeFunc = z.SomeFunc
func abc() {
// ...
v := zSomeFunc()
// ...
}
In tests you may assign another function to zSomeFunc, one that is defined in tests, and does whatever the test wants it to.
For example:
func TestAbc(t *testing.T) {
// Save current function and restore at the end:
old := zSomeFunc
defer func() { zSomeFunc = old }()
zSomeFunc = func() int {
// This will be called, do whatever you want to,
// return whatever you want to
return 1
}
// Call the tested function
abc()
// Check expected behavior
}
See related / possible duplicate:
Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)
One thing you can do is this:
import "x/y/z"
var someFunc = z.SomeFunc
func abc() {
...
v := someFunc()
...
}
And in your test file you would do this.
func Test_abc() {
someFunc = mockFunc
abc()
}
But make sure that you do this in a concurrent manner, if you have multiple TestXxx functions calling abc or setting someFunc you may be better of using a struct with a someFunc field.
Having function pointer and monkey patching it is the one of doing it. But then when you multiple functions to mock, you will have a number function pointers and unnecessarily you will have to call function using the function pointer only.
The better and the recommended idea to have an interface and make your function part of the struct implementing the interface. Once done that, you can generate mocks using some nice tools available for go.
I have been using this:
mockgen -source myModule.go -package myPackage -destination myModuleMock.go
You can install it by:
go get github.com/golang/mock
While creating a package level variable is a viable option, it comes with some restrictions. to name a few:
It discourages running parallel tests using t.Parallel() as there can be race conditions on different behaviors of mocked function.
it is dangerous as a future developer in the same package can accidentally update the implementation of this global variable.
another way is to pass along the methods you want to mock as arguments to the function to enable testability. In my case, I already had numerous clients calling this method and thus, I wanted to avoid violating the existing contracts. so, I ended up creating a wrapped function.
eg:
import (
z "x.y.z"
)
//this should replicate the type of function z from x.y.z
type operation func() resp
func wrappedAbc(op operation) {
....
resp := op()
....
}
func Abc() {
wrappedAbc(z)
}
now for testing the actual logic, you will test calls to wrappedAbc instead of abc and you would pass it a mocked operation. this will allow you to test all the business logic while not violating API contract with current clients of method Abc.
mockcompose uses an approach that allows you to generate a mocking class, you can direct mockcompose to include your selected dependency closure (any imported functions from other packages). In the mean time, it generates a cloned copy of your subject function with local overrides so that you can test against. You can embed code generation process with go generate, therefore ensure your cloned copy is always in-sync with your code changes.
Say you have a function functionThatUsesGlobalFunction that imports
Sprintf in package fmt.
func functionThatUsesGlobalFunction(
format string,
args ...interface{},
) string {
//
// skip fansy logic...
//
// call out to a global function in fmt package
return fmt.Sprintf(format, args...)
}
Your goal is to test functionThatUsesGlobalFunction with Sprintf in package fmt being mocked.
To do that, you can configure go generate with mockcompose as following:
mocks.go
//go:generate mockcompose -n mockFmt -p fmt -mock Sprintf
//go:generate mockcompose -n mockJson -p encoding/json -mock Marshal
//go:generate mockcompose -n clonedFuncs -real "functionThatUsesGlobalFunction,fmt=fmtMock"
package clonefn
go generate mockcompose will then generate plumbing classes for you, enable you to write test code as following:
package clonefn
import (
"testing"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
var fmtMock *mockFmt = &mockFmt{}
func TestClonedFuncs(t *testing.T) {
assert := require.New(t)
// setup function mocks
fmtMock.On("Sprintf", mock.Anything, mock.Anything).Return("mocked Sprintf")
// inside functionThatUsesMultileGlobalFunctions: fmt.Sprintf is mocked
assert.True(functionThatUsesGlobalFunction_clone("format", "value") == "mocked Sprintf")
}
Please checkout this for details.

Dynamic module import in Ember CLI

I have a bunch of modules defined in an Ember CLI app and each starts with the same path. I would like to import the modules into a module in the app. For example, I could write:
import post1 from 'posts/1';
import post2 from 'posts/2';
import post3 from 'posts/3';
export default Em.ObjectController.extend({
posts: Em.A(post1, post2, post3),
});
However, I do not know the module names because they are created/named on the fly by a precompiler. All I know is that the path always begins with the same string. In this case, posts.
Is there a way to import all modules that begin with a particular path? For example, how can I do something like the following:
import posts from 'posts/*';
// or
registry['posts'].forEach(postId, i) {
var path = 'posts/' + postId;
import i from path;
}
Each of the modules I want to find and import has exported an object.
I have been through the ES6 module transpiler docs but can't find much.
The ES6 spec doesn't allow you to dynamically import modules using the import keyword. All importing and exporting using the module syntax must be done statically. However, it does provide a programmatic API that you can use to dynamically import modules. This article has a great summary of it (as well as a great summary of the rest of ES6 modules).
My suggestion would be to wrap Ember's loader API in a ES6 compliant wrapper. For instance, Ember-CLI uses the require() function to get modules, so you could do something like this:
window.System = window.System || {};
window.System['import'] = function(moduleName) {
return Ember.RSVP.Promise.resolve(window.require(moduleName));
}
// ...
System.import('my-app/posts/' + postNumber).then(function(postModule) {
// ...
});
You could also use the Ember require() function directly, my way just protects you in the likely event that Ember changes their module loader.