I'm trying to learn how to implement logging using the examples/tutorial in:
http://blog.dartwatch.com/2013/05/campaign-to-use-real-logging-instead-of.html#comment-form
But having imported the libraries this line in main will not compile because the class 'PrintHandler' is not recognized and Google has not been a help in this case. My server application consists of a main and three classes. I'm new at Dart. Below I've extracted the logging code that I added.
In what library is 'PrintHandler'? Is this a class I need to write?
library server;
import 'package:logging_handlers/logging_handlers_shared.dart';
import 'package:logging/logging.dart';
final _serverLogger = new Logger("server"); // top level logger
void main() {
Logger.root.onRecord.listen(new PrintHandler()); // default PrintHandler
_serverLogger.fine("Server created");
}
class A {
}
class B {
}
class C {
}
It looks like the class was changed to LogPrintHandler but the tutorial and documentation were not updated.
Related
I have been asked to do testing in swift and I have no idea about swift
So, I was just reviewing the code and trying to make sense out of it.
I was in a file say xyzTests.swift where we wrote all the test case.
By going through the test cases written in the code, the first thing was something like this
func xyz() {
var failureMessage: String? = nil;
startSess(validity: 3)
}
In Javascript,one can only do something like this if
There is a function declared anywhere in the same file
if we are importing it from somewhere
So I searched in my file to find function declaration from startSess but wasn't able to find it. Then I clicked on jump to definition and found it some other file named utils.swift
internal func startSess(validity: Int = 1) {
}
I checked the file if there was at-least a reference of an import for at-least util but can't find any.
These are all the import statements in my code
import Foundation
#testable import session
Can someone explain me how we can use startSess?
I take it that the startSess is a function that is outside of any class then as it's being called in that way?
what #testable import session does is importing your entire workspace to be reachable from your test class. If you look in the right tab of the test file you can see that the target membership is only selected for tests (as it should be). And therefor it can't reach the rest of your code without the #testable import
See, There are various different methods to call a function from another file Some of them are as given below
(and Pardon me if I left any methods in this answer, I am open to edits :) )
As #Vollan said , importing the whole workspace , so you can access any function from any file anywhere in the project
Calling or Loading the file (in your case util.swift) and using the function in another file(xyz.swift)
ex: In xyz.swift,
func xyz() {
let a = util() //Loading the swiftfile
a.startSess(validity: 3) //using the function of swiftfile
}
making that function global which you want to use.
extension UIViewController { //In most cases UIViewController is used in all files so extending it helps
func startSess(validity: Int = 1) {
}
}
You can directly make that function global even if you are not using any extensions or any classes by using Foundation(As in any file Foundation is must imported in the Header of any SwiftFile)
Ex: - Make any SwiftFile say named abc.swift and in that file
import Foundation
func startSess(validity: Int = 1) {
//Your Code
}
Now, you can call this function by startSess(param) in any file in your whole project.
I'm attempting to create unit tests for a JenkinsShared library using Gradle in order to run the test tasks.
I've followed this tutorial which upon conclusion one has a working test suite for a shared library for functions within the vars folder (with the unit tests in src/test/groovy/*Test.groovy).
However, in our internal shared jenkins library we followed a more object oriented style and isolated functionality into a package of classes in the format: src/org/company/*.groovy.
The problem arises when attempting to import said package into a unit test class. In the tutorial, the functions are imported using the loadScript method this method fails when loading a class which is dependent on another file.
Take the class:
package tests
import org.junit.*
import com.lesfurets.jenkins.unit.*
import static groovy.test.GroovyAssert.*
import org.company.UtilFactory
class UtilFactoryTest extends BasePipelineTest {
#Test
void testCall() {
def util = UtilFactory.getUtil("hello")
assertEquals true, true
}
}
src/org/company/UtilFactory.groovy
package org.company
class UtilFactory implements Serializable {
static Util instance
static Util getUtil(script=null) {
if (!(UtilFactory.instance)) {
if (!script) {
// Throws an exception if on the first call to getUtil the
// script parameter is null.
throw new ScriptUndefinedException("script parameter null on initial call to getUtil")
}
UtilFactory.instance = new Util(script)
}
return UtilFactory.instance
}
}
class ScriptUndefinedException extends Exception {
// Parameterless Constructor
public ScriptUndefinedException() {}
// Constructor that accepts a message
public ScriptUndefinedException(String message)
{
super(message);
}
}
Which gives me the exception:
jenkins-utilities/src/test/groovy/UtilFactoryTest.groovy: 7:
unable to resolve class org.company.UtilFactory
# line 7, column 1.
import org.company.UtilFactory
This may be more of a Gradle issue than a JenkinsShared Library. I've just spent a good portion of my day trying to figure out exactly what I'm doing wrong to no avail.
I would really appreciate any help to guide me in the right direction.
This library may be helpful getting your shared libraries to work in the unit test https://github.com/stchar/pipeline-sharedlib-testharness
Consider the following Java code:
import java.util.LinkedList;
import java.util.List;
class Library {
List<String> loans = new LinkedList<>();
public List<String> searchUser(String name) {
List<String> usersFound = new LinkedList<>();
return loans;
}
}
and the following Rascal module:
module Mwe
import lang::java::flow::JavaToObjectFlow;
import lang::java::jdt::m3::AST;
import IO;
void m() {
ast = createAstFromEclipseFile(|project://test/src/test.java|, true);
fp = createOFG({ast});
print(fp);
}
The resulting flow program will be:
flowProgram({
attribute(|java+field:///Library/loans|),
method(|java+method:///Library/searchUser(java.lang.String)|,[|java+parameter:///Library/searchUser(java.lang.String)/scope(name)/scope(0)/name|]),
constructor(|java+constructor:///Library/Library()|,[])
},{
assign(|java+method:///Library/searchUser(java.lang.String)/return|,|id:///|,|java+field:///Library/loans|),
newAssign(|java+variable:///Library/searchUser(java.lang.String)/usersFound|,|java+class:///java/util/LinkedList|,|java+constructor:///java/util/LinkedList/LinkedList()|,[])
})
So, there is a new assignment of LinkedList to usersFound, but nothing comparable for loans. Why would that happen? Is that the intended behaviour?
Just checked the implementation, the field initializers are not included in the getStatements function (see lang::java::flow::JavaToObjectFlow on line 169). Similarly the static initializers of a class are ignored.
The best way forward would be to either report it as a bug, or fix it and turn it into a pull-request. (pull request is the quickest way to getting it fixed on unstable)
As a possible, yet work intensive workaround you rewrite the AST to put the field initializers inside all existing constructors (or add a constructor if there is none).
I know that
#testable import MyModule
gives ability to explore non-public members of MyModule from a "test" (built with "testTarget") module MyModuleTests.
I need the same functionality in my "non-test" module. Not in production, just in debug mode.
My question is: do you know how to do this?
And related (I think, harder question): what magic is actually happening behind #testable?
To answer your question, for debugging purposes, you can actually use this. Let's say you have a workspace MyAwesomeWkspace and a project inside MyAwesomeProject.
Now, create a new framework aka module called MyAwesomeModule. Inside that module create a non-public class called Person.
If you try to use the class Person inside MyAwesomeProject by doing import MyAwesomeModule and then something like let p = Person() you will have an error.
But if you do #testable import MyAwesomeModule, the magic happens and you can now use the class.
Basically #testable allows you to test things that you didn't declare public. The annotation only works with import as you can see it here.
So in order to work, the target is compiled with -enable-testing so that you can have access to non-public members. At least based on what's here
Because, by default, the debug build configuration is compiled with -enable-testing, the example I showed you will work. But if you change the build config to release, you'll see an error saying Module .. was not compiled for testing since the release config is not built with the flag.
The Swift access control model, as described in the Access Control
section of The Swift Programming Language (Swift 4), prevents an
external entity from accessing anything declared as internal in an app
or framework. By default, to be able to access these items from your
test code, you would need to elevate their access level to at least
public, reducing the benefits of Swift’s type safety.
Xcode provides a two-part solution to this problem:
When you set the Enable Testability build setting to Yes, which is
true by default for test builds in new projects, Xcode includes the
-enable-testing flag during compilation. This makes the Swift entities declared in the compiled module eligible for a higher level of access.
When you add the #testable attribute to an import statement for a
module compiled with testing enabled, you activate the elevated access
for that module in that scope. Classes and class members marked as
internal or public behave as if they were marked open. Other entities
marked as internal act as if they were declared public.
More here
Late edit: One of the cool parts of swift is that is open source. So if you want to dive deep into the "magic", check it out: https://github.com/apple/swift
#testable import <module_name> and -enable-testing
[Swift access modifiers]
[Swift module]
consumer side uses #testable import -> producer side should use `-enable-testing` flag
producer side: enable -enable-testing
Enable Testability(ENABLE_TESTABILITY) - YES
Other Swift Flags(OTHER_SWIFT_FLAGS) - -enable-testing
consumer side: #testable
internal(default) and public access level for class is visible for current module as open
internal(default) access level for others(struct, enum) is visible for current module as public
If you build test schema(consumer) with #testable but producer doesn't include -enable-testing you get
Module '<module_name>' was not compiled for testing
Some experiments:
SomeModule
internal class SomeInternalClass {
internal func foo() { }
}
public class SomePublicClass {
public func foo() { }
}
internal class SomeInternalStruct {
internal func foo() { }
}
internal enum SomeInternalEnum: String {
case foo = "hello world"
}
Tests: If you omit #testable next errors will occur
import XCTest
#testable import ExperimentsTests
class ExperimentsTestsTests: XCTestCase {
func testExample() throws {
let someInternalStruct = SomeInternalStruct() //Cannot find 'SomeInternalStruct' in scope
someInternalStruct.foo()
let someInternalEnum = SomeInternalEnum(rawValue: "") //Cannot find 'SomeInternalEnum' in scope
SomeInternalEnum.foo //Cannot find 'SomeInternalEnum' in scope
}
class SomePublicSubClass: SomePublicClass { //Cannot inherit from non-open class 'SomePublicClass' outside of its defining module
override func foo() { } //Overriding non-open instance method outside of its defining module
}
class SomeInternalSubClass: SomeInternalClass { //Cannot find type 'SomeInternalClass' in scope
override func foo() { } //Method does not override any method from its superclass
}
}
What is the difference between show and as in an import statement?
For example, what's the difference between
import 'dart:convert' show JSON;
and
import 'package:google_maps/google_maps.dart' as GoogleMap;
When do I use show and when should I use as?
If I switch to show GoogleMap all references to GoogleMap (e.g. GoogleMap.LatLng) objects are reported as undefined.
as and show are two different concepts.
With as you are giving the imported library a name. It's usually done to prevent a library from polluting your namespace if it has a lot of global functions. If you use as you can access all functions and classes of said library by accessing them the way you did in your example: GoogleMap.LatLng.
With show (and hide) you can pick specific classes you want to be visible in your application. For your example it would be:
import 'package:google_maps/google_maps.dart' show LatLng;
With this you would be able to access LatLng but nothing else from that library. The opposite of this is:
import 'package:google_maps/google_maps.dart' hide LatLng;
With this you would be able to access everything from that library except for LatLng.
If you want to use multiple classes with the same name you'd need to use as. You also can combine both approaches:
import 'package:google_maps/google_maps.dart' as GoogleMap show LatLng;
show case:
import 'dart:async' show Stream;
This way you only import Stream class from dart:async, so if you try to use another class from dart:async other than Stream it will throw an error.
void main() {
List data = [1, 2, 3];
Stream stream = new Stream.fromIterable(data); // doable
StreamController controller = new StreamController(); // not doable
// because you only show Stream
}
as case:
import 'dart:async' as async;
This way you import all class from dart:async and namespaced it with async keyword.
void main() {
async.StreamController controller = new async.StreamController(); // doable
List data = [1, 2, 3];
Stream stream = new Stream.fromIterable(data); // not doable
// because you namespaced it with 'async'
}
as is usually used when there are conflicting classes in your imported library, for example if you have a library 'my_library.dart' that contains a class named Stream and you also want to use Stream class from dart:async and then:
import 'dart:async';
import 'my_library.dart';
void main() {
Stream stream = new Stream.fromIterable([1, 2]);
}
This way, we don't know whether this Stream class is from async library or your own library. We have to use as :
import 'dart:async';
import 'my_library.dart' as myLib;
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // from async
myLib.Stream myCustomStream = new myLib.Stream(); // from your library
}
For show, I guess this is used when we know we only need a specific class. Also can be used when there are conflicting classes in your imported library. Let's say in your own library you have a class named CustomStream and Stream and you also want to use dart:async, but in this case you only need CustomStream from your own library.
import 'dart:async';
import 'my_library.dart';
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // not doable
// we don't know whether Stream
// is from async lib ir your own
CustomStream customStream = new CustomStream();// doable
}
Some workaround:
import 'dart:async';
import 'my_library.dart' show CustomStream;
void main() {
Stream stream = new Stream.fromIterable([1, 2]); // doable, since we only import Stream
// async lib
CustomStream customStream = new CustomStream();// doable
}
as and show keywords used with library import statement. These two keywords are optional with import keyword, But using these keywords you can provide convenience and additional information about your library importing.
show
show give restrictions to access only specific class of that library.
import 'dart:convert' show JSON;
Above dart:convert library contains more than 5 types of converters. (ascii,Base64,Latin1,Utf8 & json are some of them).
But with using show keyword you will give your application source file to access only that JSON converter class only.
warning !! :- if you try to access any other converters like ascii, Base64 or Latin1, you will get an exception.
Because using show keyword you give an restriction for only access Json class in that library api.
So if your source file want to access all the class in that library, you cannot define show keyword for that library importing.
as
Provide additional namespace for library members.
This as keyword is mostly used when a library that contains lot of global functions.
You will access static members of a library by Using the class name and . (dot operator).
eg:- ClassName.staticFun()
And also you will access instance methods and variables by using object name and . (dot operator) eg:- obj.instanceFunc()
And also library source file can have global functions. and we will access them by their name without any parental membership. eg:- func()
So when we access global functions of a different library inside our source file, we didnt have a way to seperatly identified that global function as seperate function of a different library.
But using as keyword, we can add namespace before accessing global functions of that library.
See below example to understanding real benefit of as keyword. 👇
import 'package:http/http.dart' as http;
http library contains lot of global functions. Below shows list of global functions in http library.
Accessing above http library global functions without http namespace.( import 'package:http/http.dart'; )
eg:-
1. get("url")
2. post("url")
Accessing above http library global functions with http namespace. ( import 'package:http/http.dart'as http; )
eg:-
1. http.get("url")
2. http.post("url")
So using as keyword , makes it easy to identify global functions of a different library separated from our source files' global functions.
I prefer the dart document, it's described in Libraries and visibility section.
import as: Specifying a library prefix, for example when import two libraries which has the same function name, then we can give them a prefix to specify the library.
import show: This is used to import part of the library, show only import one name of the library.
import hide: This is another one which is the opposite of the show, hide import all names except the name specified in the hide.