Is there a way to mock "import .." in python unittest? - python-unittest

I know in python by using mox, we can emulate the behaviour of a class propery or method.
But when we new a instance or a target class, it does many things in its "import ..." class.
My question is how to simulate the "import .." class behavour in mox?
in client.py
from my.test import hander
......
in hander.py:
def _doLotOfThings():
#do a lot of things
_doLotOfThings()
Is there a way to inject hander.py's _doLotOfThings() before import hander that let it does nothing?
Thanks.

Related

Hydra - Cannot override value in instantiate

I am developing a project based on the pytorch lightning + hydra template found here https://github.com/ashleve/lightning-hydra-template. I am trying to instantiate a Pytorch dataset object using hydra instantiate, overriding the default cfg value with the DictConfig object. Specifically, I have this config file:
...
training_dataset:
_target_: src.datamodules.components.baseline_datasets.FSD50K
cfg: omegaconf.dictconfig.DictConfig(content={})
mode: "training"
...
While the pytorch lightning datamodule does the following:
class AudioTagDataModule(LightningDataModule):
def __init__(self, cfg: DictConfig):
super().__init__()
self.cfg = cfg
self.save_hyperparameters(logger=False)
def setup(self, stage: Optional[str] = None):
self.trainset = instantiate(self.cfg.datamodule.training_dataset, cfg=self.cfg)
...
The rest of the code is pretty much unmodified from the template. However, when the pytorch dataset is instantiated, I get an error due to the config being empty. Checking in debug, I see that the config value is not being overridden, despite having the same name that was specified in the configs. Could someone provide some guidance on why the override is not working and how to correctly proceed? Thank!
Looking at the AudioTagDataModule, I see that the setup method passes a cfg=self.cfg keyword argument to the instantiate function. This is why the cfg setting from your training_dataset config is not showing up in your instantiated dataset; the keyword argument is taking precedence. Based on the code you posted, it would probably make sense to pass an empty DictConfig to AudioTagDataModule.__init__ instead of defining a cfg key/value in training_dataset.
Another thing: in your yaml file, you'd probably want cfg: {} instead of cfg: omegaconf.dictconfig.DictConfig(content={}), as the latter will result in the python string "omegaconf.dictconfig.DictConfig(content={})" and the former will result in an empty DictConfig.

What does Gluon SceneBuilder look for in JAR files?

Using Clojure, I'm trying to write a custom JavaFX component for use in Gluon SceneBuilder, to be loaded up from a .jar file. That is, I'd like to point SceneBuilder to the .jar with my custom class, and have the thing show up in the list of draggable items on the left.
I can make the visual structure show up with FXML only, but I'd like to include some behavior as well.
After doing the (:gen-class) stuff in my Clojure source, running lein uberjar, and using the fx:root construct in the FXML, I'm able to use the resulting class in a modified version of the official Java example.
When I instantiate my custom class in the CustomControlExample, I see evidence of the Clojure init code running (via printlns and other stuff in the graphics).
So my custom class appears to work normally. It has two constructors -- with and without a String argument, and extends from HBox. I can verify these when I view the resulting .class file in NetBeans and also using JarExplorer. The class has a ton more stuff in it, due to being a Clojure constructed class, but it has at least the same number and type of constructors as the example.
The problem is my custom component does not appear in the SceneBuilder when I import the uberjar file.
So the question is: What exactly does SceneBuilder need to see in the class to make it appear as a custom draggable component?
Here is the relevant portion of my one source file (it includes a utility library for dealing with starting up the FX runtime).
src/toyui/GridSettingsPane.clj:
(ns toyui.GridSettingsPane
(:gen-class
:extends javafx.scene.layout.HBox
:post-init post-init
:init init
:constructors {[] []
[String] []})
(:use [jfxutils.core :exclude [-main]]))
(defn -init
([]
(-init "unnamed-init"))
([name]
(println "hi from -init")
[[] []]))
(defn -post-init
([this]
(-post-init this "unnamed-post-init"))
([this name]
(println "hi from -post-init")
(jfxutils.core/app-init)
(let [loader (javafx.fxml.FXMLLoader. (clojure.java.io/resource "GridSettingsPane.fxml"))]
(.setRoot loader this)
(.setController loader this)
(.load loader)
loader))))
I discovered that SceneBuilder was using some real-time class loading. Clojure defaults to *use-context-classloader* = true, so I was able to get the class to load, sort of, by modifying the scenebuilder code a little as in my comment above. However it still was having some trouble with finding some type of resource. I figured it was still probably due to class paths and the like.
In the process I also discovered that the SceneBuilder dynamically creates a little FXML file (stream, actually), which says, among other things, <?import toyui.GridSettingsPane?>, and the runs the regular FXML loader on that stream.
So I went and modified FXMLExample to import my Clojure class from within the .fxml file and it worked.
So the conclusion is yes, my class will work as-is in the FXML when running from a regular program, but for some reason doesn't load up when the jar explorer is looking.

What's the difference between these two imports statement?

In Meteor 1.4, what's the difference between these two import statements in the client code and in the server code? Why?
Client code:
import { Items } from '../imports/api/items.js';
Server code:
import '../imports/api/items.js';
Both statements will execute the file given, however the first one will add Item to the scope. This can be useful if the file has many exports and you are only concerned with that single class/function/object/etc.
The second is used for side effects provided from importing it (like initializing a store or something like that; I confess I don't know much about meteor).
Mozilla has a great resource on the import statement https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

pyramid.util.Request source code

I'm new to Python and I am studying Pyramid to learn how to write good code. I wrote this root factory code:
class RootFactory(object):
def __acl__(self):
return [
(Allow, 'group:alfa', 'alfa'),
]
def __init__(self, request):
print(type(request))
pass
and the result shows that "request" is <class 'pyramid.util.Request'> but if I open the module pyramid.util.py, to see the source code, I do not found the class Request. I think that this class is in the module pyramid.request.py
Could someone explain how this is working?
It's an implementation detail of using config.add_request_method. When adding request methods, a new class object is created using the InstancePropertyHelper which is located in the pyramid.util module. This could probably be fixed, but at the end of the day the actual class we care about is pyramid.request.Request so you should look there for issues.

How to define a task that is called for the root project only?

When I define a task it gets called for each project in a multi-project build:
import sbt._
import Keys._
import IO._
object EnsimePlugin extends Plugin {
val ensime = TaskKey[Unit](
"generateEnsime",
"Generate the ENSIME configuration for this project")
override val projectSettings = Seq(
ensime := generateEnsime (
(thisProject in Test).value,
(update in Test).value
)
)
private def generateEnsime(proj: ResolvedProject, update: UpdateReport): Unit = {
println(s"called by ${proj.id}")
}
}
How can I define a task so that it is only called for the root project?
They are usually discouraged, but is this perhaps a valid use of a Command? e.g. like the sbt-idea plugin.
From the official docs about Aggregation:
In the project doing the aggregating, the root project in this case,
you can control aggregation per-task.
It describes aggregate key scoped to a task with the value false as:
aggregate in update := false
Use commands for session processing that would otherwise require additional steps in a task. It doesn't necessarily mean it's harder in tasks, but my understanding of commands vs tasks is that the former are better suited for session manipulation. I might be wrong, though in your particular case commands are not needed whatsoever.

Resources