GTest Automatic Mock Class - c++

For some time my old project used gmock_gen.py to generate automatically mocked classes (this is an old project from http://code.google.com/p/cppclean/ that it seems inactive and it depends on python2 that we don't want)
My question:
Is there anything on gtest environment that does the same as gmock_gen.py and supports python3, or what is the alternative to gmock_gen.py if we don't have or don't want to use python2?
Best regards,
Nuno

It seems that the conversion to python3 is very simple.
You only need to do two things and only one is required (step 2.):
you can use the python tool 2to3 to convert the code from python 2 code into python 3 code (optional)
change only one line to prevent an exception on the execution of the scrip:
gmock_gtest/generator/cpp/ast.py:908
change from:
def _GetNextToken(self):
if self.token_queue:
return self.token_queue.pop()
return next(self.tokens)
to
def _GetNextToken(self):
if self.token_queue:
return self.token_queue.pop()
return next(self.tokens, None)
and that will work.

Related

Deprecated Session.close_all() vs 'scoped_session' object has no attribute 'close_all_sessions'

I am trying to use 'drop_all' after service test fails or finishes on flask app layer:
#pytest.fixture(scope='class')
def db_connection():
db_url = TestConfig.db_url
db = SQLAlchemyORM(db_url)
db.create_all(True)
yield db_connection
db.drop_all()
When some test passes the 'drop_all' works, but when it fails the test freezes.
So, that solution solves my problem:
https://stackoverflow.com/a/44437760/3050042
Unfortunately, I got a mess with that.
When I use the 'Session.close_all()' SQLAlchemy warns:
The Session.close_all() method is deprecated and will be removed in a future release. Please refer to session.close_all_sessions().
When I change to the suggestion:
AttributeError: 'scoped_session' object has no attribute 'close_all_sessions'
Yes, I use scoped_session and pure SQLAlchemy.
How to solve this?
The close_all_sessions function is defined at the top level of sqlalchemy.orm.session. At the time of writing this answer, here is how it looks. Thus, you can use it as follows.
from sqlalchemy.orm.session import close_all_sessions
close_all_sessions()

Changes to django-appengine-toolkit for Windows

I want to use django-appengine-toolkit to provide symlinks needed by Appengine to include dependencies in the production runtime environment as discussed here. Unfortunately, I ran into an "AttributeError: 'module' object has no attribute 'symlink' " problem. A bit of research took me to this solution for apptrace, which indicated it was due to running the code on Windows. Adding this change with the arguments for
kdll.CreateSymbolicLinkA(srcname, dstname, 0)
changed to
kdll.CreateSymbolicLinkA(path, dest, 0)
at _utils.py at line 62 (as shown here) fixed the AttributeError and allowed the code to complete and autogenerate appengine_config.py with the necessary sys.path information.
Unfortunately, the dependencies were not populated under the 'libs' directory and I fear that my Python skills failed me at that point.
Can anyone identify what further code changes are needed to populate the dependencies?
since I really needed this ASAP, I ended up modifying the _utils.py file on appengine_toolkit:
def make_simlinks(dest_dir, paths_list):
"""
TODO docstrings
"""
for path in paths_list:
dest = os.path.join(dest_dir, os.path.split(path)[-1])
if os.path.exists(dest):
if os.path.islink(dest):
os.remove(dest)
else:
sys.stderr.write('A file or dir named {} already exists, skipping...\n'.format(dest))
continue
try:
os.symlink(path, dest)
except:
import shutil
sys.stdout.write('Couldn\'t create symlink copying files instead ...\n')
shutil.copytree(path, dest)
Basically if symlinking fails, I just copy everything. Not the cleanest hack but it works

How can I create a JSON webservice to store and retrieve data from a simple properties file?

How can I create a Java or Javascript JSON webservice to retrieve data from a simple properties file? My intention is to uses this as a global property storage for a Jenkins instance that runs many Unit tests. The master property file also needs to be capable of being manually edited and stored in source control.
I am just wondering what method people would recommend that would be the easiest for a junior level programmer like me. I need read capability at miniumum but, and if its not too hard, write capability also. Therefore, that means it is not required to be REST.
If something like this already exists in Java or Groovy, a link to that resource would be appreciated. I am a SoapUI expert but I am unsure if a mock service could do this sort of thing.
I found something like this in Ruby but I could not get it to work as I am not a Ruby programmer at all.
There are a multitude of Java REST frameworks, but I'm most familiar with Jersey so here's a Groovy script that gives a simple read capability to a properties file.
#Grapes([
#Grab(group='org.glassfish.jersey.containers', module='jersey-container-grizzly2-http', version='2.0'),
#Grab(group='org.glassfish.jersey.core', module='jersey-server', version='2.0'),
#Grab(group='org.glassfish.jersey.media', module='jersey-media-json-jackson', version='2.0')
])
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory
import org.glassfish.jersey.jackson.JacksonFeature
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
#Path("properties")
class PropertiesResource {
#GET
#Produces("application/json")
Properties get() {
new File("test.properties").withReader { Reader reader ->
Properties p = new Properties()
p.load(reader)
return p
}
}
}
def rc = new org.glassfish.jersey.server.ResourceConfig(PropertiesResource, JacksonFeature);
GrizzlyHttpServerFactory.createHttpServer('http://localhost:8080/'.toURI(), rc).start()
System.console().readLine("Press any key to exit...")
Unfortunately, since Jersey uses the 3.1 version of the asm library, there are conflicts with Groovy's 4.0 version of asm unless you run the script using the groovy-all embeddable jar (it won't work by just calling groovy on the command-line and passing the script). I also had to supply an Apache Ivy dependency. (Hopefully the Groovy team will resolve these in the next release--the asm one in particular has caused me grief in the past.) So you can call it like this (supply the full paths to the classpath jars):
java -cp ivy-2.2.0.jar:groovy-all-2.1.6.jar groovy.lang.GroovyShell restProperties.groovy
All you have to do is create a properties file named test.properties, then copy the above script into a file named restProperties.groovy, then run via the above command line. Then you can run the following in Unix to try it out.
curl http://localhost:8080/properties
And it will return a JSON map of your properties file.

How do I run some code after every build in scons?

I'm looking for a way to register somthing like an end-build callback in scons. For example, I'm doing something like this right now:
def print_build_summary():
failures = SCons.Script.GetBuildFailures()
notifyExe = 'notify-send '
if len(failures) > 0:
notifyExe = notifyExe + ' --urgency=critical Build Failed'
else:
notifyExe = notifyExe + ' --urgency=normal Build Succeed'
os.system(notifyExe)
atexit.register(print_build_summary)
This only works in non-interactive mode. I'd like to be able to pop up something like this at the end of every build, specifically, when running multiple 'build' commands in an interactive scons session.
The only suggestions I've found, looking around, seem to be to use the dependency system or the AddPostAction call to glom this on. It doesn't seem quite right to me to do it that way, since it's not really a dependency (it's not even really a part of the build, strictly speaking) - it's just a static bit of code that needs to be run at the end of every build.
Thanks!
I don't think there's anything wrong with using the dependency system to resolve this. This is how I normally do it:
def finish( target, source, env ):
raise Exception( 'DO IT' )
finish_command = Command( 'finish', [], finish )
Depends( finish_command, DEFAULT_TARGETS )
Default( finish_command )
This creates a command that depends on the default targets for it's execution (so you know it'll always run last - see DEFAULT_TARGETS in scons manual). Hope this helps.
Ive been looking into this and havent found that SCons offers anything that would help. This seems like quite a usefull feature, maybe the SCons developers are watching these threads and will take the suggestion...
I looked at the source code and figured out how to do it. I'll try to suggest this change to the SCons developers on scons.org.
If you're interested, the file is engine/SCons/Script/Main.py, and the function is _build_targets(). At the end of this funcion, you would simply need to add a call to a user supplied callback. Of course this solution would not be very useful if you build on several different machines in your network, since you would have to port the change everywhere its needed, but if you're only building on one machine, then maybe you could make the change until/if SCons officially provides a solution.
Let me know if you need help implementing the change, and I'll see what I can do.
Another option would be to wrap the call to SCons, and have the wrapper script perform the desired actions, but that wouldnt help in SCons interactive mode.
Hope this helps,
Brady
EDIT:
I create a feature request for this: http://scons.tigris.org/issues/show_bug.cgi?id=2834

Setting up SCons to Autolint

I'm using google's cpplint.py to verify source code in my project meets the standards set forth in the Google C++ Style Guide. We use SCons to build so I'd like to automate the process by having SCons first read in all of our .h and .cc files and then run cpplint.py on them, only building a file if it passes. The issues are as follows:
In SCons how do I pre-hook the build process? No file should be compiled until it passes linting.
cpplint doesn't return an exit code. How do I run a command in SCons and check whether the result matches a regular expression? I.E., how do I get the text being output?
The project is large, whatever the solution to #1 and #2 it should run concurrently when the -j option is passed to SCons.
I need a whitelist that allows some files to skip the lint check.
One way to do this is to monkey patch the object emitter function, which turns C++ code into linkable object files. There are 2 such emitter functions; one for static objects and one for shared objects. Here is an example that you can copy paste into a SConstruct:
import sys
import SCons.Defaults
import SCons.Builder
OriginalShared = SCons.Defaults.SharedObjectEmitter
OriginalStatic = SCons.Defaults.StaticObjectEmitter
def DoLint(env, source):
for s in source:
env.Lint(s.srcnode().path + ".lint", s)
def SharedObjectEmitter(target, source, env):
DoLint(env, source)
return OriginalShared(target, source, env)
def StaticObjectEmitter(target, source, env):
DoLint(env, source)
return OriginalStatic(target, source, env)
SCons.Defaults.SharedObjectEmitter = SharedObjectEmitter
SCons.Defaults.StaticObjectEmitter = StaticObjectEmitter
linter = SCons.Builder.Builder(
action=['$PYTHON $LINT $LINT_OPTIONS $SOURCE','date > $TARGET'],
suffix='.lint',
src_suffix='.cpp')
# actual build
env = Environment()
env.Append(BUILDERS={'Lint': linter})
env["PYTHON"] = sys.executable
env["LINT"] = "cpplint.py"
env["LINT_OPTIONS"] = ["--filter=-whitespace,+whitespace/tab", "--verbose=3"]
env.Program("test", Glob("*.cpp"))
There's nothing too tricky about it really. You'd set LINT to the path to your cpplint.py copy, and set appropriate LINT_OPTIONS for your project. The only warty bit is creating a TARGET file if the check passes using the command line date program. If you want to be cross platform then that'd have to change.
Adding a whitelist is now just regular Python code, something like:
whitelist = """"
src/legacy_code.cpp
src/by_the_PHB.cpp
"""".split()
def DoLint(env, source):
for s in source:
src = s.srcnode().path
if src not in whitelist:
env.Lint( + ".lint", s)
It seems cpplint.py does output the correct error status. When there are errors it returns 1, otherwise it returns 0. So there's no extra work to do there. If the lint check fails, it will fail the build.
This solution works with -j, but the C++ files may compile as there are no implicit dependencies between the lint fake output and the object file target. You can add an explicit env.Depends in there to force that the ".lint" output depend on the object target. As is it's probably enough, since the build itself will fail (scons gives a non-zero return code) if there are any remaining lint issues even after all the C++ compiles. For completeness the depends code would be something like this in the DoLint function:
def DoLint(env, source, target):
for i in range(len(source)):
s = source[i]
out = env.Lint(s.srcnode().path + ".lint", s)
env.Depends(target[i], out)
AddPreAction seems to be what you are looking for, from the manpage:
AddPreAction(target, action)
env.AddPreAction(target, action)
Arranges for the specified action to be performed before the specified target is built. T
Also see http://benno.id.au/blog/2006/08/27/filtergensplint for an example.
See my github for a pair of scons scripts complete with an example source tree. It uses Google's cpplint.py.
https://github.com/xyzisinus/scons-tidbits