Is it possible to ignore classes from being instrumented based off of package folder? - byte-buddy

We currently have ByteBuddy injecting some code into every method of a particular package, for example, com.contoso.widgets. This is working great!
However, we also have tests in the tst folder for the same package, for which we do not want to have ByteBuddy instrument on (but we do want the entities under test -- in the same package -- to be instrumented!).
Is there a way to define AgentBuilder so that it ignores all classes that come from tst, rather than src? It feels like I might be missing something obvious but haven't been successful after combing through the docs.

ByteBuddy works on byte code level, not on file system level. Have you tried to exclude tests by class name, e.g.
.type(not(nameEndsWith("Test").or(nameEndsWith("IT"))))
Or maybe you want to try something like excluding all classes containing methods annotated by #Test - untested, but maybe similar to this:
.type((typeDescription, classLoader, module, classBeingRedefined, protectionDomain) ->
typeDescription
.getDeclaredMethods()
.filter(inDefinedShape -> inDefinedShape.getDeclaredAnnotations().isAnnotationPresent(Test.class))
.size() == 0
)

Byte Buddy supports a RawMatcher where any type's ProtectionDomain is supplied. A protection domain offers access to the types's CodeSource from which you can find the file system location of its class file.
Do however note that this value depends on class loader, OS, packaging format and deployment. It might work for a standardized test environment but can fail you if you derive from it. It's therefore recommended to rely on something more structured.

Related

Lithium: How do I change the location Connections' and similar classes look for adapters

I've been trying to get Connections to use a customised adapter located at app/extensions/data/source/database/adapter/. I thought extending the Connections class and replacing
protected static $_adapters = 'data.source';
with
protected static $_adapters = 'adapter.extension.data.source';
and changing the connections class used at the top of app/config/bootstrap/connections.php to use app\extensions\data\Connections;
would be enough to get it started. However this just leads to a load of errors where the code is still trying to use the original Connections class.
Is there a simple way to achieve this, or do I have to recreate the entire set of classes from lithium/data in extensions with rewritten class references?
EDIT:
Turns out I was going about this the wrong way. After following Nate Abele's advice, Libraries::path('adapter') showed me where to correctly place the MySql.php file I'm trying to override ;-)
For dealing with how named classes (i.e. services, in the abstract) are located, you want to take a look at the Libraries class, specifically the paths() method, which allows you to define how class paths are looked up.
You can also look at the associated definitions, like locate() and $_paths, to give you an idea of what the default configuration looks like.
Finally, note that the Connections class is 'special' since it defines one path dynamically, based on the supplied configuration: http://li3.me/docs/api/lithium/1.0.x/lithium/data/Connections::_class()
This should help you reconfigure how your classes are organized without extending/overriding anything. Generally you shouldn't need to do that unless you need some drastically different behavior.

How to enumerate all java classes in a directory in jython

I find it tedious to import a java class in jython because of the long package names. e.g. com.example.x.y.z.SomeClass. It's a lot of typing. I want to import by using only the simple name of the class (SomeClass in my example). Is there a way of achieving it? Current solution in my head is to enumerate all the classes in the classpath and prepare a map of simple class name to the complete package name like -
SomeClass -> com.example.x.y.z.SomeClass
SomeOtherClass -> com.example.p.q.r.SomeOtherClass
etc. Then call a function something like below-
def intelligent_import(simple_class_name):
#No error checking, simplified for clarity
package_name = dict[simle_class_name]
simple_class_name = __import__(package_name)
for each of the classes. The only problem is that I don't know a method to enumearte all classes in a directory. Is there's a better way to do this? If not a method to enumerate all java classes in a directory will do.
This is a bit of a hack, I'm sure there's better our there, but if everything else fails, remember that JAR files are just ZIPs, and that each class will have a .class file in the jar.
However, rather than hacking the import mechanism like this, I'd rather just use an IDE with proper autocompletion (i.e. Eclipse/PyDev, it's the only one that can do it reliably in my experience), and rock the ctrl-space.

BDD and outside-in approach, how to start with testing

All,
I'm trying to grasp all the outside-in TDD and BDD stuff and would like you to help me to get it.
Let's say I need to implement Config Parameters functionality working as follows:
there are parameters in file and in database
both groups have to be merged into one parameters set
parameters from database should override those from files
Now I'd like to implement this with outside-in approach, and I stuck just at the beginning. Hope you can help me to get going.
My questions are:
What test should I start with? I just have sth as follows:
class ConfigurationAssemblerTest {
#Test
public void itShouldResultWithEmptyConfigurationWhenBothSourcesAreEmpty() {
ConfigurationAssembler assembler = new ConfigurationAssembler();
// what to put here ?
Configuration config = assembler.getConfiguration();
assertTrue(config.isEmpty());
}
}
I don't know yet what dependencies I'll end with. I don't know how I'm gonna write all that stuff yet and so on.
What should I put in this test to make it valid? Should I mock something? If so how to define those dependencies?
If you could please show me the path to go with this, write some plan, some tests skeletons, what to do and in what order it'd be super-cool. I know it's a lot of writing, so maybe you can point me to any resources? All the resources about outside-in approach I've found were about simple cases with no dependencies etc.
And two questions to mocking approach.
if mocking is about interactions and their verification, does it mean that there should not be state assertions in such tests (only mock verifications) ?
if we replace something that doesn't exist yet with mock just for test, do we replace it later with real version?
Thanks in advance.
Ok, that's indeed a lot of stuff. Let's start from the end:
Mocking is not only about 'interactions and their verification', this would be only one half of the story. In fact, you're using it in two different ways:
Checking, if a certain call was made, and eventually also checking the arguments of the call (this is the 'interactions and verification' part).
Using mocks to replace dependencies of the class-under-test (CUT), eventually setting up return values on the mock objects as required. Here, you use mock objects to isolate the CUT from the rest of the system (so that you can handle the CUT as an isolated 'unit', which sort of runs in a sandbox).
I'd call the first form dynamic or 'interaction-based' unit testing, it uses the Mocking frameworks call verification methods. The second one is more traditional, 'static' unit testing which asserts a fact.
You shouldn't ever have the need to 'replace something that doesn't exist yet' (apart from the fact that this is - logically seen - completely impossible). If you feel like you need to do this, then this is a clear indication that you're trying to make the second step before the first.
Regarding your notion of 'outside-in approach': To be honest, I've never heard of this before, so it doesn't seem to be a very prominent concept - and obviously not a very helpful one, because it seems to confuse things more than clarifying them (at least for the moment).
Now onto your first question: (What test should I start with?):
First things first - you need some mechanism to read the configuration values from file and database, and this functionality should be encapsulated in separate helper classes (you need, among other things, a clean Separation of concerns for effectively doing TDD - this usually is totally underemphasized when introducing TDD/BDD). I'd suggest an interface (e.g. IConfigurationReader) which has two implementations (one for the file stuff and one for the database, e.g. FileConfigurationReader and DatabaseConfigurationReader). In TDD (not necessarily with a BDD approach) you would also have corresponding test fixtures. These fixtures would cover test cases like 'What happens if the underlying data store contains no/invalid/valid/other special values?'. This is what I'd advice you to start with.
Only then - with the reading mechanism in operation and your ConfigurationAssembler class having the necessary dependencies - you would start to write tests for/implement the ConfigurationAssembler class. Your test then could look like this (Because I'm a C#/.NET guy, I don't know the appropriate Java tools. So I'm using pseudo-code here):
class ConfigurationAssemblerTest {
#Test
public void itShouldResultWithEmptyConfigurationWhenBothSourcesAreEmpty() {
IConfigurationReader fileConfigMock = new [Mock of FileConfigurationReader];
fileConfigMock.[WhenAskedForConfigValues].[ReturnEmpty];
IConfigurationReader dbConfigMock = new [Mock of DatabaseConfigurationReader];
dbConfigMock.[WhenAskedForConfigValues].[ReturnEmpty];
ConfigurationAssembler assembler = new ConfigurationAssembler(fileConfigMock, dbConfigMock);
Configuration config = assembler.getConfiguration();
assertTrue(config.isEmpty());
}
}
Two things are important here:
The two reader objects are injected to the ConfigurationAssembler from outside via its constructor - this technique is called Dependency Injection. It is very helpful and important architectural principle, which generally leads to a better and cleaner architecture (and greatly helps in unit testing, especially when using mock objects).
The test now asserts exactly what it states: The ConfigurationAssembler returns ('assembles') an empty config when the underlying reading mechanisms on their part return an empty result set. And because we're using mock objects to provide the config values, the test runs in complete isolation. We can be sure that we're testing only the correct functioning of the ConfigurationAssembler class (its handling of empty values, namely), and nothing else.
Oh, and maybe it's easier for you to start with TDD instead of BDD, because BDD is only a subset of TDD and builds on top of the concepts of TDD. So you can only do (and understand) BDD effectively when you know TDD.
HTH!

How to find and remove unused class files from a project

My XCode project has grown somewhat, and I know that there are class files in there which are no longer being used. Is there an easy way to find all of these and remove them?
If the class files just sit in your project without being part of a target, just click on the project itself in the tree view, so you see all files in the table. Make sure you see the "Target" column in the table view, iterate through your targets and find the files that don't have a check anywhere -> they are no longer compiled.
But if you still compile the classes and they are no longer used, that case is a bit more difficult. Check out this project
http://www.karppinen.fi/analysistool/#dependency-graphs
You could create a dependency graph and try to find orphaned classes that way.
Edit: Link went dead, but there still seem to be projects of Objective-C dependency graphs around, for example https://github.com/nst/objc_dep
if they are C or C++ symbols, then you can just let the linker do the work for you.
if you're looking to remove objc symbols, then try to refactor the class name (e.g. to rename the class), and preview the dependencies that it turns up. if you reference classes/selectors/etc. by strings then... it may not be so effective. unfortunately, you often have to also test manually, to verify that removing a class does not break anything. remember that resources (like xibs) may reference/load objc classes as well.
This is a tricky question due to how dynamic objective-c is as you can never guarantee that a class is not going to be used.
Consider if you generate a class name and a selector at run time and then look up that class, instantiate that class and then call a method on that newly created object using that newly created selector. No where in your code do you explicitly name and instantiate that object but you are able to use it anyways. You could get that class name and selector name from anywhere outside of your code, even from some data from a server some where. How would you ever know which class is not going to be used? Because of this there are no tools that are able to perform what you are requesting.
Searching the project with the class name might be an option, thought it may not be the best solution. Specially it might be time consuming when you have many classes.

Dynamicly load dll in fitnesse fixture

I'm trying to write a FitNesse fixture against an interface (in c#). I want to be able to have the fixture dynamically load the implementation from a dll (so that I can use the same tests against different implementations of the same interface...i.e. mock data, live data, etc.). I have a init method in my fixture that takes 2 strings, a class name and a dll name. I call Assembly.LoadFrom(dllname) in the method. I get the following error with that call: "Invalid Directory on URL".
Any ideas? It sounds like the dll name is getting mangled somehow in the translation...
The table looks like this:
|Init Provider From Dll|SlmLicenseDataErrorProvider|TestModelProvider.dll|
Thanks in advance...
-Robert
You may want to add a !path somewhere to point to the location of your assemblies. By default Fitnesse.Net (or FitSharp, or whatever it is these days) usually defaults its working directory to the location of the FitServer.exe executable (or SlimServer.exe or whatever it is these days). If your assembly isn't in that directory, or in the default assembly search paths or the GAC then fitnesse may simply not be finding it?