Testng Tests is igored - testng-dataprovider

#DataProvider(name = "Standard_ask")
public Iterator<Object[]> txtReader() throws IOException{
File asks = new File("src/test/resources/testdata/standard_ask.txt");
FileReader reader = new FileReader(asks);
BufferedReader bufferReader = new BufferedReader(reader);
String[] c =new String[1000];
String s = null;
ArrayList all = new ArrayList();
while ((s = bufferReader.readLine()) != null)
all.add(s);
Iterator ask = all.iterator();
System.out.println(ask.next());
return ask;
}
// just add test assertion to test why this test is igored
#Test(dataProvider = "Standard_ask", alwaysRun = true)
public void testSimilarityFaqTest(Iterator<Object[]> a) throws IOException {
System.out.println(a.next());
if (a.hasNext() == true){
String strResponse = httpClientUtil.doGetForSingleParam(url,a.next());
JSONObject jsonResponse = JSONObject.parseObject(strResponse);
Assert.assertEquals(jsonResponse,1);
}
I got below test result
可以教我怎么使用吗
java.lang.ClassCastException: java.lang.String cannot be cast to
[Ljava.lang.Object;
at org.testng.internal.Parameters$2.next(Parameters.java:537)
at org.testng.internal.Parameters$2.next(Parameters.java:522)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1165)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:73)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Test ignored.
===============================================
Default Suite
Total tests run: 1, Failures: 1, Skips: 0
anybody has any testng issus above,or could you please tell me why?

It should be
#Test(dataProvider = "Standard_ask", alwaysRun = true)
public void testSimilarityFaqTest(Object a) throws IOException {
//omitted

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

getting java.nio.BufferUnderflowException while reading dbf file after using dbaseFileWriter.write(vals);

I'm using DbaseFileReader and DBaseFileWriter to read and update records in a dbf file. When I read the file first there is no error while opening DBF file but after I write some values to DBF using below method I'm getting the following Error
I've checked the value types in Object[] array, both type and count of values are equal to dbf file fields.
public static boolean updateFeatureAtts(String shpFile, Map<String, Object> attsFeature) throws IOException {
String file = CN.getMapDataFolder() + CN.FOLDER_LAYERS + "/" + shpFile.replace(".shp", ".dbf");
DbaseFileWriter dbaseFileWriter = null;
DbaseFileReader dbaseFileReader = null;
ReadableByteChannel dbfChannel = null;
WritableByteChannel writableByteChannel = null;
FileOutputStream fileOutputStream = null;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
dbfChannel = Channels.newChannel(inputStream);
dbaseFileReader = new DbaseFileReader(dbfChannel, true, Charset.forName("Windows-1256"));
DbaseFileHeader header = dbaseFileReader.getHeader();
for (Iterator<Map.Entry<String, Object>> iterator = attsFeature.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Object> entry = iterator.next();
if (entry.getKey().equals("FID")) {
iterator.remove();
}
}
fileOutputStream = new FileOutputStream(file);
writableByteChannel = Channels.newChannel(fileOutputStream);
dbaseFileWriter = new DbaseFileWriter(header, writableByteChannel, Charset.forName("UTF-8"), TimeZone.getDefault());
Object[] vals = attsFeature.values().toArray();
dbaseFileWriter.write(vals);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (dbaseFileReader != null)
dbaseFileReader.close();
if (dbaseFileWriter != null)
dbaseFileWriter.close();
}
return true;
}
this is the error
java.nio.BufferUnderflowException at
java.nio.DirectByteBuffer.get(DirectByteBuffer.java: 164)
at org.geotools.data.shapefile.dbf.DbaseFileReader.read(DbaseFileReader.java: 417)
at org.geotools.data.shapefile.dbf.DbaseFileReader.readRow(DbaseFileReader.java: 314)
at com.edsab.gedat.util.DBaseFileHandler.findRecord(DBaseFileHandler.java: 174)
at com.edsab.gedat.adapter.AttributePagerAdapter.instantiateItem(AttributePagerAdapter.java: 102)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java: 1003)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1217)
at android.support.v4.view.ViewPager.populate(ViewPager.java: 1085)
at android.support.v4.view.ViewPager$3.run(ViewPager.java: 273)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java: 777)
at android.view.Choreographer.doCallbacks(Choreographer.java: 590)
at android.view.Choreographer.doFrame(Choreographer.java: 559)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java: 763)
at android.os.Handler.handleCallback(Handler.java: 739)
at android.os.Handler.dispatchMessage(Handler.java: 95)
at android.os.Looper.loop(Looper.java: 145)
at android.app.ActivityThread.main(ActivityThread.java: 6918)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 1199)

Quasar multi fibers warning

I am new to quasar and I tried doing this.
Basically I get a warning the fiber is blocking a thread. Why ? can I not do something like below ?
Thanks
//in my my testclass I have this
String websites[] = {"http://www.google.com",""http://www.lol.com",""http://www.somenoneexistantwebsite.com"};
for(int i=0; i < websites.length ; i++){
TestApp.getWebsiteHTML(websites[i]);
}
//in TestApp
public static void getWebsiteHTML(String webURL) throws IOException, InterruptedException, Exception {
new Fiber<Void>(new SuspendableRunnable() {
#Override
public void run() throws SuspendExecution, InterruptedException {
WebInfo mywi = new WebInfo();
mywi.getHTML(webURL);
}
}).start().join();
}
//in WebInfo
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Have a look at the "Runaway fibers" sub-section in the docs.
HttpURLConnection is thread-blocking so in order to avoid stealing threads from the fiber scheduler for too much time (which risks killing your Quasar-based application's performance) you should rather use an HTTP client integrated with Quasar (or integrate one yourself).

How to hit the database from junit using JPA

I am writing junit test case, how to hit the database from junit using jpa.
I wrote the code for but got the following exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named smsPU
I added provide in src/test/resources/META-INF/persistent.xml file, But i got the that error.
I am posting the my code also please check where is the wrong in this code.
public class SmsBeanTest {
private SmsBean smsBean;
private SmsNotification notification;
private EntityManagerFactory entity;
private EntityManager em;
#Before
public void setUp() throws Exception {
String CONFIG_ATTR_NAME = "webappConfig";
smsBean = new SmsBean();
ServletContext ctx = mock(ServletContext.class);
Configuration config = new Configuration();
config.initProperties("syniverse-sms.properties");
when(ctx.getAttribute(CONFIG_ATTR_NAME)).thenReturn(config);
smsBean.setServletContext(ctx);
**//em = mock(EntityManager.class);
Properties prop = new Properties();
// Ensure RESOURCE_LOCAL transactions is used.
prop.put(TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal connection pool
prop.put(JDBC_DRIVER, "com.mysql.jdbc.Driver");
prop.put(JDBC_URL, "jdbc:mysql://localhost:3306/platform_service_db");
prop.put(JDBC_USER, "root");
prop.put(JDBC_PASSWORD, "root");
prop.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
"src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar");
entity = Persistence.createEntityManagerFactory("smsPU", prop);
System.out.println(entity);
em = entity.createEntityManager(prop);
smsBean.setEm(em);**
// doNothing().when(em).persist(notification);
smsBean.init();
notification = new SmsNotification();
}
#After
public void tearDown() throws Exception {
smsBean = null;
notification = null;
//entity.close();
//em.close();
}
#Test
public void testSendSms() {
SmsNotificationDTO sms = new SmsNotificationDTO();
sms.setToAddress("9985291980");
sms.setMessage("Sending Message...");
try {
SyniverseDispatcher disp = mock(SyniverseDispatcher.class);
SyniverseResponse resp = new SyniverseResponse();
resp.setResponseStr("1234");
String smsTo = notification.getDestination();
String smsMsg = notification.getMessage() + new Date().getTime();
String urlStr = smsBean.getHostname() + "?user=" + smsBean.getUser() + "&pass=" + smsBean.getPass() + "&smsfrom=" + smsBean.getShortCode() + "&smsto=" + sms.getToAddress() + "&smsmsg=" + sms.getMessage();
SyniverseRequest req = new SyniverseRequest();
req.setRequestURL(urlStr);
when(disp.dispatch(req)).thenReturn(resp);
smsBean.sendSms(sms);
assertNotNull(sms.getToAddress());
assertEquals(10, sms.getToAddress().length());
assertNotNull(sms.getMessage());
assertEquals("1234", resp.getResponseStr());
} catch (SmsException e) {
fail(e.getMessage());
}
}
}
please help me,
it can't find the persistance.xml because you have it incorrectly defined. "src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar" the jar file shouldn't be listed.

exception in java

private String getEmailTemplateWithActualValueForAccount(String template, Account account) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Map<String,String> map = new HashMap<String, String>();
List<String> listTags = new ArrayList<String>();
Map<Method, String> methodList = new HashMap<Method, String>();
int startIndex=0;
int endIndex=0;
for(int i=0; i<template.length(); i++)
{
char ch = template.charAt(i);
if(ch=='$')
startIndex = i+1;
if(ch=='#')
{
endIndex = i+1;
listTags.add(template.substring(startIndex,endIndex));
}
}
Method[] methods = Account.class.getMethods();
for (Method method : methods) {
String methodName = method.getName();
if(method.getName().startsWith("get"))
{
methodList.put(method, methodName.substring(3,methodName.length()).toUpperCase()+"#");
}
}
Set<Method> methodKeySet = methodList.keySet();
for (Method method : methodKeySet) {
for (String string : listTags) {
if(methodList.get(method).equals(string))
{
try{
Object obj = method.invoke(account, null);
if(obj!=null)
map.put(string, obj.toString());
}catch(NullPointerException e){
}
}
}
}
final StringBuilder list = new StringBuilder( "\\$(" );
for( final String key: map.keySet() )
{
list.append( key );
list.append( "|" );
}
list.append( "[^\\s\\S])" );
Pattern pattern = Pattern.compile( list.toString() );
Matcher matcher = pattern.matcher( template );
final StringBuffer stringBuffer = new StringBuffer();
while( matcher.find() ){
final String string = matcher.group( 1 );
matcher.appendReplacement( stringBuffer, map.get( string ));
}
matcher.appendTail( stringBuffer );
return stringBuffer.toString();
}
I got an exception at line of code "Object obj = method.invoke(account, null);"
Code is perfectly working but as this code is in scheduler it will create an log at every 20 second on jboss server.
The invoke method of Method throws an InvocationTargetException "if the underlying method throws an exception", according to the Javadoc. So you better look into the method that you are invoking to find out why it's throwing an exception. Check the exception stack trace for the root cause.
Instead of catching NullPointerException, you should catch InvocationTargetException, and check the wrapped exception.